重写属性的方法

2024-10-01 19:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类,它有一个属性作为另一个类的对象。第三个类继承自第一个类,在这里,我要重写属性的方法

class Car:
    def __init__(self, door):
        self.door = door

class Door:
    def __init__(self, color):
        self.color = color
    def change_color(self):
        pass

class CarConstruct(Car):
    def __init__(self):
        super(CarConstruct, self).__init__(Door('red'))
        # Here, I want to override self.door.change_color method

在这种情况下,最好的方法是什么


Tags: 对象方法self属性initdefpasschange
1条回答
网友
1楼 · 发布于 2024-10-01 19:32:11

这种技术称为"monkey patching"。一般来说,应该避免这样做,因为这样会使代码很难理解和推理。除非你有很好的理由,否则就要避免。一个好的原因可能是mock a method in unit tests

如果您仍然想在一个对象上只修补一个方法self.door-check out this answer

相关问题 更多 >

    热门问题