Skip to main content
 首页 » 编程设计

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

2025年05月04日13傻小

我有一些短类 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返回['radio']来自 __init__ :

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']