Skip to content

Instantly share code, notes, and snippets.

@kako-nawao
Last active April 11, 2017 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kako-nawao/2bc6eb62a12892998e39c996b5827b8d to your computer and use it in GitHub Desktop.
Save kako-nawao/2bc6eb62a12892998e39c996b5827b8d to your computer and use it in GitHub Desktop.
Example of a factory superclass, which constructor returns a new instance of the correct subclass for a given parameter.
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