我有一个类,它有一个属性作为另一个类的对象。第三个类继承自第一个类,在这里,我要重写属性的方法
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
在这种情况下,最好的方法是什么
这种技术称为"monkey patching"。一般来说,应该避免这样做,因为这样会使代码很难理解和推理。除非你有很好的理由,否则就要避免。一个好的原因可能是mock a method in unit tests
如果您仍然想在一个对象上只修补一个方法
self.door
-check out this answer相关问题 更多 >
编程相关推荐