如何在python的子类中设置父类的属性?

时间:2019-05-13 20:14:47

标签: python-3.x

我有两类,一类是Vehicle,一类是BMW,我知道我可以在Vehicle的属性上创建颜色。但是我如何在BMW类中设置属性 但我仍然能够以bmw.info,color的身份访问颜色?我可以做类似的事情吗?

class Vehicle:
    def __init__(self, name): 
        self.name = name
        self._color = None

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, color):
        self._color = color
class BMW:
    def __init__(self, name):
        self.info = Vehicle(name)
#can I do something like
class Vehicle:
    def __init__(self, name): 
        self.name = name

class BMW:
    def __init__(self, name):
        self.info = Vehicle(name)

    setattr(self.info, "color", None)

    @info.property
    def color(self):
        return self._color

    @info.color.setter
    def color(self, color):
        self._color = color

bmw = BMW('sister')
print(bmw.info.color)
bmw.info.color = 'red'
print(bmw.info.color)

0 个答案:

没有答案