我上了一堂简短的课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)
Run Code Online (Sandbox Code Playgroud)
我创建一个对象:
car1 = Car('opel','astra','blue',[])
Run Code Online (Sandbox Code Playgroud)
当我尝试通过以下方式添加其他附件时:
car1 += ['wheel']
Run Code Online (Sandbox Code Playgroud)
它打印:
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)
Run Code Online (Sandbox Code Playgroud)
但是后来我打电话给:
car1.accesories
Run Code Online (Sandbox Code Playgroud)
要么
print(car1)
Run Code Online (Sandbox Code Playgroud)
它分别给了我:
car1 = Car('opel','astra','blue',[])
Run Code Online (Sandbox Code Playgroud)
和
car1 += ['wheel']
Run Code Online (Sandbox Code Playgroud)
为什么对象不记得添加到列表的值?
那是因为你有:
return Car(self.brand, self.model, self.color, self.accesories)
Run Code Online (Sandbox Code Playgroud)
在您的__iadd__方法,这将重新self.accessories回到['radio']自__init__:
self.accesories = ['radio']
Run Code Online (Sandbox Code Playgroud)
操作:
car1 += ['wheel']
Run Code Online (Sandbox Code Playgroud)
将__iadd__方法返回的值设置为name car1,并将accessories其设置为from __init__,['radio']因此['radio']在访问时将得到car1.accessories。
也许您想使用parameter的值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']
Run Code Online (Sandbox Code Playgroud)