簡體   English   中英

為什么sympy覆蓋`__new__`而不是`__init__`?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM