【问题标题】:Recursion, Polymorphism and Inheritance confusion in PythonPython中的递归、多态和继承混淆
【发布时间】:2020-10-27 02:59:01
【问题描述】:

我在 Python 3.8 中有两个类:A 和 B,其中 B 继承自 A,两个类都有同名的方法,因此 B 类的方法覆盖 A 类的方法,B 中的方法有一个参数加号。

B中的函数调用super().method(condition),A中的函数递归调用self.method(condition),我期望的结果是当我做super ().method(condition)在B中,然后self.method(condition)在A中再次执行A类的方法,但是得到的结果是它试图执行B 中的方法,由于缺少参数而引发错误。 这是代码:

class A():
    def method(self, condition):
        if condition:
            print('from A')
        else:
            self.method(True)

class B(A):
    def method(self, condition, other):
        if condition:
            print('from B')
        else:
            super().method(False)

b = B()
b.method(False, 0)

这是错误:

TypeError: method() 缺少 1 个必需的位置参数:'other'

【问题讨论】:

  • Python 正在做它应该做的事情。 object.method() 调用适用于object 的方法版本。从哪里调用它并不重要。如果您使用类型为 `B 的对象调用它,那么它将调用 B 的方法实现。

标签: python recursion inheritance polymorphism


【解决方案1】:

请参阅我上面的评论。最简单的解决方案是创建一个私有方法,这样就不会混淆了。

class A():
    def __method(self, condition):
        if condition:
            print('from A')
        else:
            self.__method(True)
    
    def method(self, condition):
        self.__method(condition)

【讨论】:

    【解决方案2】:
       # The parameters should be same in both the methods.
        class A():
            def method(self, condition,other):
                if condition:
                    print('from A')
                else:
                    self.method(True)
    
        class B(A):
            def method(self, condition, other):
                if condition:
                    print('from B')
                else:
                    super().method(False)
    
        b = B()
        b.method(False, 0)
    
    
                      OR 
        class A():
            def method(self, condition):
                if condition:
                    print('from A')
                else:
                    self.method(True)
    
        class B(A):
            def method(self, condition):
                if condition:
                    print('from B')
                else:
                    super().method(False)
    
        b = B()
        b.method(False, 0)
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2012-09-13
    • 2015-04-27
    相关资源
    最近更新 更多