调用Python子类的父方法有问题吗?

问题描述 投票:0回答:1
import abc
class Parent(abc.ABC):
 
   def is_valid(self, thing):
      return thing is not None

class Child(Parent):
   def is_valid(self, thing):
      return super(Parent, self).is_valid(thing) and thing > 5

a = Child()
print(a.is_valid(6))

这给出了 AttributeError: 'super' 对象没有属性 'is_valid'

我做错了什么?

python inheritance
1个回答
0
投票

super
的第一个参数告诉属性查找以方法解析顺序 (MRO) 中该参数之后的类开始。你根本不需要任何参数super
class Child(Parent):
   def is_valid(self, thing):
      return super().is_valid(thing) and thing > 5

但是如果您想提供它们,正确的第一个参数是 
Child

,而不是

Parent
class Child(Parent):
   def is_valid(self, thing):
      return super(Child, self).is_valid(thing) and thing > 5

通过指定 
Parent

作为第一个参数,您需要从

is_valid
获取
object
属性,而
具有该属性。 >>> Child.mro() [<class '__main__.Child'>, <class '__main__.Parent'>, <class 'abc.ABC'>, <class 'object'>]

© www.soinside.com 2019 - 2024. All rights reserved.