[英]Why does sympy override `__new__` instead of `__init__`?
sympy
中的每個對象都是Basic類的子類,它們都使用__new__
而不使用__init__
,並且大多數情況是這樣的
def __new__(cls, some, parameter, **others):
obj = parentclass.__new__(cls, **others)
obj.some = some
obj.parameter = parameter
return obj
像這樣使用__init__
什么區別
def __init__(self, some, parameter, **others):
parentclass.__init__(self, **others) # or super().__init__(...)
self.some = some
self.parameter = parameter
?
看一下Number 。 他們希望對象的類靈活。 Number(...) => Int/Float/...
__init__
無法實現。
此外, __init__
將獲得__new__
的參數,但是您不需要原始參數,請參見matexpr.py,或者您需要將它們調整為適用於__new__
已經做過的事情(例如__reduce__
)。
大多數對象定義了自己的__slots__
因此可以為它們分配固定的屬性。 可以在__new__
和__init__
進行分配。 我看不到只需要設置一個新的__init__
就可以進行設置,而無需執行其他任何操作-正如Martijn Pieters和user4815162342 [source]指出的,這些對象是不可變的。
有時__init__
被調用,如果您更改類,則一次或兩次:
class X(object):
def __new__(self): # sorry but self is the class I apologize!
obj = object.__new__(Y)
return obj
def __init__(self):
print 1
>>> class Y(object):
def __init__(self):
print 2
>>> X() # no __init__ call, limiting you to stay in the class hierarchy
<__main__.Y object at 0x7f287e769350>
>>> class Y(X):
def __init__(self):
print 2
>>> X() # one __init__ call
2
<__main__.Y object at 0x7f287e7693d0>
>>> class X(object):
def __new__(self):
obj = Y()
return obj
def __init__(self):
print 1
>>> class Y(X):
def __new__(self):
return object.__new__(self)
def __init__(self):
print 2
>>> X() # __init__ called twice, structure copied from number.py
2
2
<__main__.Y object at 0x7f287e7692d0>
如果我錯了,請糾正我。 我不認為這個答案是完整的,但是這些都是我發現值得鼓勵的原因,除了Martijn Pieters和user4815162342提到的對象應該是不可變的以外,我不鼓勵使用__init__
[源]
等待2次降票刪除答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.