Python利用new創建一個類的對象


class MyClass(BaseClass):
    def __new__(cls, *args, **kwargs):
        return super(MyClass, cls).__new__(cls, *args, **kwargs)

super並不是一個函數,而是一個類名,形如super(B, cls)事實上調用了super類的初始化函數,產生了一個super對象。Python Manuals上介紹:
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type.
Note: super() only works for new-style classes.

super接收兩個參數,兩個參數的類型之間需要有繼承關系,否則會報:
TypeError: super(type, obj): obj must be an instance or subtype of type  

T.__new__(S, ...) return a new object with type S, a subtype of T


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM