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

时间:2019-07-26 22:40:45

标签: python class add

我有一些简短的课程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']

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

2 个答案:

答案 0 :(得分:5)

那是因为您有:

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

在您的__iadd__方法中,该方法会将self.accessories['radio']重设为__init__

self.accesories = ['radio']

操作:

car1 += ['wheel']

将从__iadd__方法返回的值设置为名称car1,将accessories中的__init__设置为['radio'],因此您将获得{{1 }}访问['radio']


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

accessories

答案 1 :(得分:2)

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

替换您的长return
return self

输出:

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