如何在初始化类 python 期间覆盖实例变量属性行为



我有一个类 车辆的属性为颜色,宝马类具有car_type作为车辆的实例变量 从下面我从宝马获得颜色属性但是有什么方法可以覆盖宝马级车辆的行为颜色属性吗?所以当我 调用bmw.car_type它不仅执行颜色属性,还从 MyColor 返回值

class Vehicle:
def __init__(self):
self._color = 'blue'
@property
def color(self):
return self._color
class BMW:
def __init__(self):
self.car_type = Vehicle()
@property
def mycolor(self):
return 'extra string from BMW'
bmw = BMW()
print(bmw.mycolor) # extra string form BMW
print(bmw.car_type.color) #blue
#I want to override the color property inside BMW class so I can call bmw.car_type.color to get the string without create extra property
print(bmw.car_type.color) #blue + extra string form BMW

在您的代码段中,宝马类不继承车辆,如果我理解正确,这就是您想要的宝马类的行为:

class Vehicle:
def __init__(self):
self._color = 'blue'
@property
def color(self):
return self._color
class BMW(Vehicle):
def __init__(self):
super().__init__()
@property
def color(self):
return self._color + 'extra string from BMW'
car = Vehicle()
print(car.color) #blue
bmw = BMW()
print(bmw.color) #blue extra string from BMW'

最新更新