本文介绍了python中type和type .__ new__有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在写一个元类,却不小心是这样的:
I was writing a metaclass and accidentally did it like this:
class MetaCls(type): def __new__(cls, name, bases, dict): return type(name, bases, dict)...而不是这样:
class MetaCls(type): def __new__(cls, name, bases, dict): return type.__new__(cls, name, bases, dict)这两个元类之间到底有什么区别?更具体地说,是什么导致第一个不能正常工作(元类未调用某些类)?
What exactly is the difference between these two metaclasses? And more specifically, what caused the first one to not work properly (some classes weren't called into by the metaclass)?
推荐答案在第一个示例中,您正在创建一个全新的类:
In the first example you're creating a whole new class:
>>> class MetaA(type): ... def __new__(cls, name, bases, dct): ... print 'MetaA.__new__' ... return type(name, bases, dct) ... def __init__(cls, name, bases, dct): ... print 'MetaA.__init__' ... >>> class A(object): ... __metaclass__ = MetaA ... MetaA.__new__ >>>而在第二种情况下,您将调用父级的__new__:
while in the second case you're calling parent's __new__:
>>> class MetaA(type): ... def __new__(cls, name, bases, dct): ... print 'MetaA.__new__' ... return type.__new__(cls, name, bases, dct) ... def __init__(cls, name, bases, dct): ... print 'MetaA.__init__' ... >>> class A(object): ... __metaclass__ = MetaA ... MetaA.__new__ MetaA.__init__ >>>更多推荐
python中type和type .
发布评论