Python 3.x 无法在OOP(Python)中使用setter和getter更改值
我无法更改福特汽车的速度,即使使用setter和getter将速度更新为新值(我不想使用赋值运算符)。以下是我的代码:Python 3.x 无法在OOP(Python)中使用setter和getter更改值,python-3.x,oop,getter-setter,Python 3.x,Oop,Getter Setter,我无法更改福特汽车的速度,即使使用setter和getter将速度更新为新值(我不想使用赋值运算符)。以下是我的代码: class Car: def __init__(self,speed,color): self.speed = speed self.color = color def set_speed(self,value): self.value=value def get_speed(self):
class Car:
def __init__(self,speed,color):
self.speed = speed
self.color = color
def set_speed(self,value):
self.value=value
def get_speed(self):
return self.speed
ford = Car(100,'black')
audi = Car(200,'red')
bmw = Car(250,'white')
ford.set_speed(400)
print(ford.get_speed())
print(ford.color)
为什么我没有得到福特的速度为400,即使设置了它?
我得到的输出是-
100
黑色您正在更改setter中的attibute
值,而不是您在getter中返回的speed属性。
只需将setter中的代码更改为:
self.speed=value
您没有设置速度。只需将self.value=value
更改为self.speed=value