【发布时间】:2021-12-30 21:07:53
【问题描述】:
我遇到了这个方法继承的例子:
子类Manager继承自父类Employee,修改了它的give_raise()方法,同时在新实现中也调用了Employee.give_raise()。
# Parent class
class Employee:
def __init__(self, name, salary=30000):
self.name = name
self.salary = salary
def give_raise(self, amount):
self.salary += amount
# Child class
class Manager(Employee):
def display(self):
print("Manager ", self.name)
def __init__(self, name, salary=50000, project=None):
Employee.__init__(self, name, salary)
self.project = project
# Modify the give_raise method
def give_raise(self, amount, bonus=1.05):
new_amount = amount * bonus
# Call the parent method
Employee.give_raise(self, new_amount)
mngr = Manager("John Smith", 80000)
mngr.give_raise(5000)
print(mngr.salary)
我的问题是:这不是有点令人费解吗?
我得到了类继承。但是在同名的子方法中调用父方法?
在Manager类中写give_raise()不是更好吗:
def give_raise(self, amount, bonus):
new_amount = amount * bonus
self.salary += amount
对我来说,只有调用 Parent.method() 是一种完全不同的方法并且需要大量代码时才有意义
【问题讨论】:
-
是的,这完全有道理,如果父实现永远不会改变。如果可能的话,您只需将相同的代码复制并粘贴到两个位置,并且必须记住每次都更新。你重复自己的次数越多,当你发现自己一直在重复错误的事情时,情况就越糟糕。
-
give_raise封装了两件事:用于定义加薪的特定类别的奖金,以及实际增加薪水的动作。前者可以存储为类属性,后者无需在子类中重新定义即可访问。 -
它允许扩展父方法的功能,而无需将其所有代码复制到子类中。