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")

錯誤信息spa

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

新式類與舊式類 super繼承方式不一樣code

更改方法blog

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")
相關文章
相關標籤/搜索