super方法的使用问题

class A:
    def __new__(cls, name):
        print("A.__new__called")
        return super().__new__(cls,name)
    def __init__(self,name):
        self.name = name
        print ("A.__init__ called")

    def __str__(self):
        return self.name
s= A("xxx")
print(s)


class B:
    def __new__(cls, *args, **kwargs):
        print("B.__new__ called")

错误信息

Traceback (most recent call last):
.....
    return super().__new__(cls.name)
AttributeError: type object 'A' has no attribute 'name'
A.__new__called

新式类与旧式类 super继承方式不同

更改方法

class A:
    def __new__(cls,name):
        print("A.__new__called")
        return super().__new__(cls)
    def __init__(self,name):
        self.name = name
        print ("A.__init__ called")

    def __str__(self):
        return self.name
s= A("xxx")
print(s)


class B:
    def __new__(cls, *args, **kwargs):
        print("B.__new__ called")

 

posted @ 2017-03-21 20:29  王喜山  阅读(193)  评论(0编辑  收藏  举报