`__init__`不能做什么`__new__`可以做什么? [英] What can `__init__` do that `__new__` cannot?
问题描述
在Python中,__new__
用于初始化不可变类型,而__init__
通常用于初始化可变类型.如果将__init__
从该语言中删除,该怎么办(轻松)了?
In Python, __new__
is used to initialize immutable types and __init__
typically initializes mutable types. If __init__
were removed from the language, what could no longer be done (easily)?
例如,
class A:
def __init__(self, *, x, **kwargs):
super().__init__(**kwargs)
self.x = x
class B(A):
def __init__(self, y=2, **kwargs):
super().__init__(**kwargs)
self.y = y
可以使用__new__
这样重写:
class A_N:
def __new__(cls, *, x, **kwargs):
obj = super().__new__(cls, **kwargs)
obj.x = x
return obj
class B_N(A_N):
def __new__(cls, y=2, **kwargs):
obj = super().__new__(cls, **kwargs)
obj.y = y
return obj
问题范围的澄清:这不是关于如何使用__init__
和__new__
或它们之间有什么区别的问题.这是一个问题,如果从语言中删除__init__
会发生什么.有什么坏事吗?任何事情都会变得很难或不可能吗?
Clarification for scope of question: This is not a question about how __init__
and __new__
are used or what is the difference between them. This is a question about what would happen if __init__
were removed from the language. Would anything break? Would anything become a lot harder or impossible to do?
推荐答案
在__init__
中可以做的所有事情都可以在__new__
中完成.
Everything you can do in __init__
can also be done in __new__
.
然后,为什么要使用__init__
?
因为您不必将实例存储在变量(示例代码中的obj
)中,以后也不必将其返回.您可以专注于自己真正想做的事-初始化可变对象.
Then, why use __init__
?
Because you don't have to store instance in variable (obj
in your example code), and later bother returning it. You can focus on what you realy want to do – initializing mutable object.
这篇关于`__init__`不能做什么`__new__`可以做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!