【问题标题】:Is overriding a parent class method with a different signature a good practice? [duplicate]用不同的签名覆盖父类方法是一种好习惯吗? [复制]
【发布时间】:2021-03-24 05:55:22
【问题描述】:

我有这个带有父/子类的小例子。我知道代码将毫无问题地运行,但是用具有不同签名的方法覆盖父方法是否是一种好习惯? PyCharm 似乎并不认为这是一个好主意:

方法“Daughter.do()”的签名与类“Mother”中基方法的签名不匹配

有关信息,调用 Parent 方法 do 应该执行 do(self) 不是 do(self, c)

代码示例:

class Parent:

    def __init__(self):
        self._a = "a"

    def do(self):
        print("Parent: {}".format(self._a))


class Child(Parent):

    def __init__(self):
        Parent.__init__(self)
        self._b = "b"

    def do(self, c):
        print("Child: {}".format(self._a))
        print("Child: {}".format(self._b))
        print("Child: {}".format(c))

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    这是一种不好的做法。例如打破Liskov substitution principle;如果你有一个函数,它需要一个 Mother 实例,并在其上调用 do(),当你将 Daughter 传递给它时它将失败。

    看这个例子:

    def call_do(mother: Mother) -> None:
         mother.do()
    

    应该能够将Mother的实例,或其任何子类的实例传递给call_do

    但如果你现在这样做:

    daughter = Daughter()
    call_do(daughter)
    

    您将收到TypeError

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 2015-05-16
      • 2019-07-18
      • 2011-02-28
      • 2015-01-08
      相关资源
      最近更新 更多