Skip to content

Instantly share code, notes, and snippets.

@tonyyang-svail
Created July 30, 2018 22:45
Show Gist options
  • Save tonyyang-svail/26fbe64b33bd80795c62a77988c0b5f6 to your computer and use it in GitHub Desktop.
Save tonyyang-svail/26fbe64b33bd80795c62a77988c0b5f6 to your computer and use it in GitHub Desktop.
class MyClass(object):
pass
# is identical to
# type(name, bases, dct)
# - name is a string giving the name of the class to be constructed
# - bases is a tuple giving the parent classes of the class to be constructed
# - dct is a dictionary of the attributes and methods of the class to be constructed
MyClass = type('MyClass', (), {})
# Example: Registry
class DBInterfaceMeta(type):
# we use __init__ rather than __new__ here because we want
# to modify attributes of the class *after* they have been
# created
def __init__(cls, name, bases, dct):
if not hasattr(cls, 'registry'):
# this is the base class. Create an empty registry
cls.registry = {}
else:
# this is a derived class. Add cls to the registry
interface_id = name.lower()
cls.registry[interface_id] = cls
super(DBInterfaceMeta, cls).__init__(name, bases, dct)
class DBInterface(object):
__metaclass__ = DBInterfaceMeta
print(DBInterface.registry)
# {}
class FirstInterface(DBInterface):
pass
class SecondInterface(DBInterface):
pass
class SecondInterfaceModified(SecondInterface):
pass
print(DBInterface.registry)
# {'firstinterface': <class '__main__.FirstInterface'>, 'secondinterface': <class '__main__.SecondInterface'>, 'secondinterfacemodified': <class '__main__.SecondInterfaceModified'>}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment