Skip to content

Instantly share code, notes, and snippets.

Last active April 11, 2017 22:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment