Example of a factory superclass, which constructor returns a new instance of the correct subclass for a given parameter.
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
class Animal(object): | |
def __new__(cls, common_name, *args, **kwargs): | |
for subclass in cls.__subclasses__(): | |
if subclass.common_name == common_name: | |
return object.__new__(subclass, *args, **kwargs) | |
raise ValueError('No animal species matched for common name "{}"'.format(common_name)) | |
class CanisLupusFamiliaris(Animal): | |
common_name = 'dog' | |
class FelisCatus(Animal): | |
common_name = 'cat' | |
# Get a dog instance: OK | |
dog = Animal('dog') | |
assert type(dog) == CanisLupusFamiliaris | |
# Get a cat instance: OK | |
cat = Animal('cat') | |
assert type(cat) == FelisCatus | |
# Get spider instance: error (no animal species matched) | |
Animal('spider') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment