python中type和type .

编程入门 行业动态 更新时间:2024-10-26 14:32:29
本文介绍了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 .

本文发布于:2023-11-07 04:15:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:python   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!