重写是类的属性,可以更改其基类之一提供的方法的实现。
覆盖是OOP的一个非常重要的部分,因为它使继承能够充分利用其能力。通过使用方法重写,一个类可以“复制”另一个类,避免重复的代码,同时可以增强或自定义其一部分。因此,方法重写是继承机制的一部分。
在Python中,方法的覆盖是通过简单地在子类中定义与父类中的方法名称相同的方法来实现的。在对象中定义方法时,使后者能够满足该方法调用,因此不会祖先的实现。
class Parent(object): def __init__(self): self.value = 4 def get_value(self): return self.value class Child(Parent): def get_value(self): return self.value + 1
现在,子对象的行为有所不同
>>> c = Child()>>> c.get_value() 5