在定义元类时,是否有任何理由选择__new__ over __init__? [英] Is there any reason to choose __new__ over __init__ when defining a metaclass?
问题描述
我一直设置元类如下:
类SomeMetaClass(type):
def __new__ (cls,name,bases,dict):
#do stuff here
遇到一个定义如下的元类:
类SomeMetaClass(type):
def __init __ ,bases,dict):
#do stuff here
有任何理由
更新:请记住,我要询问使用 __ new __
和 __ init __
。我已经明白了他们在另一个类之间的区别。但在元类中,我不能使用 __ new __
来实现缓存,因为 __ new __
元类。如果要在创建类之前更改属性dict,或更改基本元组,使用 __ new __
。到时间 __ init __
看到参数,类对象已经存在。此外,如果要返回某个新创建的类型类以外的其他类,则必须使用 __ new __
。
另一方面,在时间 __ init __
运行时,类确实存在。
编辑:将改变的措辞更改为其中一个成员对象的引用。使得更清楚的是,通过对象,我的意思是类对象。
I've always set up metaclasses something like this:
class SomeMetaClass(type):
def __new__(cls, name, bases, dict):
#do stuff here
But I just came across a metaclass that was defined like this:
class SomeMetaClass(type):
def __init__(self, name, bases, dict):
#do stuff here
Is there any reason to prefer one over the other?
Update: Bear in mind that I'm asking about using __new__
and __init__
in a metaclass. I already understand the difference between them in another class. But in a metaclass, I can't use __new__
to implement caching because __new__
is only called upon class creation in a metaclass.
If you want to alter the attributes dict before the class is created, or change the bases tuple, you have to use __new__
. By the time __init__
sees the arguments, the class object already exists. Also, you have to use __new__
if you want to return something other than a newly created class of the type in question.
On the other hand, by the time __init__
runs, the class does exist. Thus, you can do things like give a reference to the just-created class to one of its member objects.
Edit: changed wording to make it more clear that by "object", I mean class-object.
这篇关于在定义元类时,是否有任何理由选择__new__ over __init__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!