【问题标题】:What's the point of method inheritance and calling Parent.method()?方法继承和调用 Parent.method() 有什么意义?
【发布时间】: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 封装了两件事:用于定义加薪的特定类别的奖金,以及实际增加薪水的动作。前者可以存储为类属性,后者无需在子类中重新定义即可访问。
  • 它允许扩展父方法的功能,而无需将其所有代码复制到子类中。

标签: python oop


【解决方案1】:

Parent.give_raise 可以以一种不需要被覆盖的方式定义,以便自定义 提升不同员工类型获得的内容。

例如,

class Employee:
    default_salary = 30000

    def __init__(self, name, salary=None, bonus=1, **kwargs):
        super().__init__(**kwargs)
        if salary is None:
            salary = self.default_salary

        self.name = name
        self.salary = salary
        self.bonus_multiplier = bonus

    def give_raise(self, amount):
        self.salary += amount * self.bonus_multiplier


class Manager(Employee):
    default_salary = 50000

    def display(self):
        print("Manager ", self.name)

    def __init__(self, *, project=None, **kwargs):
        if 'bonus' not in kwargs:
            kwargs['bonus'] = 1.05
        super.__init__(**kwargs)
        self.project = project


mngr = Manager(name="John Smith", salary=80000)
mngr.give_raise(5000)
print(mngr.salary)

【讨论】:

    【解决方案2】:

    我同意你最初的问题,因为实现有点复杂,无助于清楚地传达预期的用途。方法继承的主要目标是鼓励类层次结构中可重用、封装的行为。这样,派生类可以添加一些功能或覆盖底层功能(或保留它并添加其他功能)。

    【讨论】:

      猜你喜欢
      • 2010-11-04
      • 1970-01-01
      • 2021-11-13
      • 2020-07-14
      • 2011-08-28
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多