简体   繁体   中英

How to override instance variable property behavior during initialize class python

I have one class Vehicle with property as color and BMW class has car_type as instance variable from Vehicle from the following I get color property from BMW But is there any way I can overwrite the behavior color property of Vehicle in BMW class? so when I call bmw.car_type it execute not only color property but also return the value from 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

In your snippet BMW class does not inherit Vehicle, if I understood correctly this is the behavior you want for BMW class:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM