对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 部分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值