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