Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

A dynamic form of the class statement.

These 2 methods are equivalent.
# method 1
class X(object):
    a = 1

# method 2
X = type('X', (object,), dict(a=1))

Another metaclass example

Taken from this c.l.p. thead
Non-metaclass version
# 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 

Metaclass version
# 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 

Simple example of meta-class

Use metaclass to define the representation
of a class (not an instance).
>>> class Pretty(type):
...     def __str__(cls):
...         return '<Class ' + cls.__name__ +'>'
...     
>>> class Foo(object):
...     __metaclass__ = Pretty
...     
>>> str(Foo)
'<Class Foo>'
>>> 

Representation of an instance can be done using class.
Representation of a class can be done using meta-class.
The code is adapted from this blog post.

Declarative metaclass

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 cls

When 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 instance

You 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.
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS