Last active
December 12, 2019 00:42
-
-
Save cflamant/5c5a1fe537ab2cbe719aed7c4fe1b1fa to your computer and use it in GitHub Desktop.
Code to demonstrate how to create subclasses dynamically when the superclass is not known before execution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Code to demonstrate dynamically creating subclasses for a | |
superclass that is not known before execution. | |
General idea: you want to make a subclass that is a baby animal, | |
but you don't know whether it will be a Human or Sheep (or possibly | |
another animal from a different module) until the code is run. | |
By creating the subclass dynamically (using the "type" function), | |
you can avoid writing a separate subclass for each superclass possibility. | |
Cedric Flamant | |
""" | |
class Human(): | |
def __init__(self, name): | |
print("Created Human") | |
print(f"My name is {name}") | |
self.name = name | |
def think(self): | |
return "HELLO" | |
def speak(self): | |
print(self.think()) | |
class Sheep(): | |
def __init__(self, name): | |
print("Created Sheep") | |
print(f"Baah baah baah {name}") | |
self.name = name | |
def think(self): | |
return "BAAAAH" | |
def speak(self): | |
print(self.think()) | |
### Functions for dynamic subclass, Baby ### | |
def _constructor(self, name): | |
super(self.__class__, self).__init__(name) | |
print("It's a baby!") | |
def _babythink(self): | |
# make the thought lowercase | |
return super(self.__class__, self).think().lower() | |
############################################## | |
# Main part of script. Superclasses "Human" and | |
# "Sheep" are passed at runtime | |
# make new class BabyHuman dynamically | |
BabyHuman = type("BabyHuman", | |
(Human,), | |
{"__init__": _constructor, | |
"think": _babythink, | |
}) | |
# make new class BabySheep dynamically | |
BabySheep = type("BabySheep", | |
(Sheep,), | |
{"__init__": _constructor, | |
"think": _babythink, | |
}) | |
# Construct an adult human | |
human = Human("Jacob") | |
human.speak() | |
# output: | |
# Created Human | |
# My name is Jacob | |
# HELLO | |
# Construct a baby human | |
babyhuman = BabyHuman("Timmy") | |
babyhuman.speak() | |
# output: | |
# Created Human | |
# My name is Timmy | |
# It's a baby! | |
# hello | |
# Construct a baby sheep | |
babysheep = BabySheep("Woolie") | |
babysheep.speak() | |
# output: | |
# Created Sheep | |
# Baah baah baah Woolie | |
# It's a baby! | |
# baaaah |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment