为什么 class 属性不记住通过 __iadd__ 方法添加的值?

Why doesn't class attribute remember values added via __iadd__ method?

我有一些短class Car:

class Car:

    def __init__(self, brand, model, color, accesories):
        self.brand = brand
        self.model = model
        self.color = color
        self.accesories = ['radio']

    def __str__(self):
        return " accessories {}".format(self.accesories)

    def __iadd__(self, other):
        self.accesories.extend(other)
        print(self.accesories)
        return Car(self.brand, self.model, self.color, self.accesories)

我创建了一个对象:

car1 = Car('opel','astra','blue',[])

当我尝试添加额外的附件时:

car1 += ['wheel']

它打印:

['radio', 'wheel']

但是当我稍后打电话时:

car1.accesories

print(car1)

它分别给我:

['radio']

accessories ['radio']

为什么对象不记得添加到列表中的值?

那是因为你有:

return Car(self.brand, self.model, self.color, self.accesories)

在您的 __iadd__ 方法中,它将 self.accessories__init__:

重置回 ['radio']
self.accesories = ['radio']

操作:

car1 += ['wheel']

将从 __iadd__ 方法返回的值设置为名称 car1,并将 accessories__init__ 设置为 ['radio'] 因此你会得到 ['radio'] 当访问 car1.accessories.


也许您想使用参数 accessories 的值作为属性:

class Car:

    def __init__(self, brand, model, color, accesories=None):
        self.brand = brand
        self.model = model
        self.color = color
        self.accesories = accessories if accessories else ['radio']

您返回了一个新初始化的对象,而不是您刚刚更新的对象。用简单的

替换你的长return
return self

输出:

['radio', 'wheel']
 accessories ['radio', 'wheel']