A dynamic form of the class statement.
# method 1 class X(object): a = 1 # method 2 X = type('X', (object,), dict(a=1))
11390 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
# method 1 class X(object): a = 1 # method 2 X = type('X', (object,), dict(a=1))
# using C as parent class C(object): observers = [] @classmethod def showObservers(cls): print cls.observers # D1, D2 only inherit class method class D1(C): observers = [] # redundant class D2(C): observers = [] # redundant
# C uses M as metaclass class M(type): def __init__(cls, name, bases, dict): cls.observers = [] def showObservers(cls): print cls.observers class C(object): __metaclass__ = M # D1, D2 inherit both methods and variables class D1(C): pass class D2(C): pass
>>> class Pretty(type): ... def __str__(cls): ... return '<Class ' + cls.__name__ +'>' ... >>> class Foo(object): ... __metaclass__ = Pretty ... >>> str(Foo) '<Class Foo>' >>>
class DeclarativeMeta(type): def __new__(meta, class_name, bases, new_attrs): cls = type.__new__(meta, class_name, bases, new_attrs) if new_attrs.has_key('__classinit__'): cls.__classinit__ = staticmethod(cls.__classinit__.im_func) cls.__classinit__(cls, new_attrs) return cls
class YourClass(object): __metaclass__ = DeclarativeMeta # ... and other class variables def __classinit__(cls, new_attrs): # do whatever you want with the new class # ... def __init__(self): # do whatever you want with the new instance