本文主要是介绍Python继承中的元类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
继承中的元类
首先写代码测试的时候发现问题
class MetaClassTest1class(type):def __new__(cls, clsname, bases, dct):dct['test'] = 1return super(MetaClassTest1class, cls).__new__(cls, clsname, bases, dct)class MetaClassTest2class(type):def __new__(cls, clsname, bases, dct):dct['test'] = 2return super(MetaClassTest2class, cls).__new__(cls, clsname, bases, dct)class MetaClassTest3class(type):def __new__(cls, clsname, bases, dct):dct['test'] = 3return super(MetaClassTest3class, cls).__new__(cls, clsname, bases, dct)__metaclass__ = MetaClassTest1classclass Foo():__metaclass__ = MetaClassTest2classpassclass FooChild(Foo):__metaclass__ = MetaClassTest3classpassf = Foo()
print f.test
运行的结果是
TypeError Traceback (most recent call last)
<ipython-input-52-81f8a2dedcb4> in <module>()24 pass25
---> 26 class FooChild(Foo):27 __metaclass__ = MetaClassTest3class28 pass<ipython-input-52-81f8a2dedcb4> in __new__(cls, clsname, bases, dct)
这篇关于Python继承中的元类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!