Join the DZone community and get the full member experience.Join For Free
Metaclass is like a black magic in python. I wouldn't learn it if not necessary to read someone's code. SqlObject uses it. So, if I want to port it to pys60 Dbms, I need to learn metaclass. Fortunately, this one is not too much to understand.
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 clsWhen you use it you do this
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 instanceYou use this when you want a subclass to have some magic done to it when it is first defined. What you say in __classinit__ will get done to the new subclass, eg. create more methods, properties, etc.
Opinions expressed by DZone contributors are their own.