对python元类概念的理解

以下内摘自《Python 中的元类编

如果说类是对象实例的模板,那么元类就是类的模板,类的工厂

清单 1. 老式的 Python 1.5.2 类工厂

Python 1.5.2 (#0, Jun 27 1999, 11:23:01) [...]

Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam

>>> def class_with_method(func):

...     class klass: pass

...     setattr(klass, func.__name__, func)

...     return klass

...

>>> def say_foo(self): print 'foo'

...

>>> Foo = class_with_method(say_foo)

>>> foo = Foo()

>>> foo.say_foo()

foo

工厂函数 class_with_method() 动态地创建一个类,并返回该类,这个类包含传递给该工厂的方法/函数。在返回该类之前,在函数体内操作类自身。 new 模块提供了更简洁的编码方式,但其中的选项与类工厂体内定制代码的选项不同,例如:

清单 2. new 模块中的类工厂

>>> from new import classobj

>>> Foo2 = classobj('Foo2',(Foo,),{'bar':lambda self:'bar'})

>>> Foo2().bar()

'bar'

>>> Foo2().say_foo()

foo

 

元类的魔力

清单 3. 作为类工厂元类的 type

>>> X = type('X',(),{'foo':lambda self:'foo'})

>>> X, X().foo()

(<class '__main__.X'>, 'foo')

 

清单 4. 作为类工厂的 type 后代

>>> class ChattyType(type):

...     def __new__(cls, name, bases, dct):

...         print "Allocating memory for class", name

...         return type.__new__(cls, name, bases, dct)

...     def __init__(cls, name, bases, dct):

...         print "Init'ing (configuring) class", name

...         super(ChattyType, cls).__init__(name, bases, dct)

...

>>> X = ChattyType('X',(),{'foo':lambda self:'foo'})

Allocating memory for class X

Init'ing (configuring) class X

>>> X, X().foo()

(<class '__main__.X'>, 'foo')

 

清单 5. 将类方法附加在所生成的类上

>>> class Printable(type):

...     def whoami(cls): print "I am a", cls.__name__

...

>>> Foo = Printable('Foo',(),{})

>>> Foo.whoami()

I am a Foo

>>> Printable.whoami()

Traceback (most recent call last):

TypeError:  unbound method whoami() [...]

 清单 6. 用类属性设置元类

>>> class Bar:

...     __metaclass__ = Printable

...     def foomethod(self): print 'foo'

...

>>> Bar.whoami()

I am a Bar

>>> Bar().foomethod()

foo

 

 

 

 

参考:

Python 中的元类编

Python 中的元类编程,第 2

Python 中的元类编程,第 3

posted on 2011-08-31 18:04  yaksea  阅读(860)  评论(0编辑  收藏  举报