我创建了一个Child
类,该类使用Parent
中不存在的GrandParent
类女巫中的方法。但是在Child.__init__()
类中,我不想从Parent.__init__()
中获得某些效果,而是调用了GrandParent.__init__()
class GrandParent():
...
class Parent(GrandParent):
def __init__(self):
GrandParent.__init__(self)
...
class Child(Parent):
def __init__(self):
GrandParent.__init__(self)
...
使用此代码,我从pylint得到了下一个警告
W0233: __init__ method from a non direct base class 'GrandParent' is called (non-parent-init-called)
W0231: __init__ method from base class 'Parent' is not called (super-init-not-called)
解决此警告的正确方法是什么?
((或对儿童禁用此警告是正确的解决方案?)
class Child(Parent):
def __init__(self): # pylint: disable=W0233
GrandParent.__init__() # pylint: disable=W0231
...
您可以尝试多种方式,例如:
GrandParent.__init__(self)
super().super().__init__(self)
super(GrandParent, self).__init__()
但是错误仍然存在:
super-init-not-called
bad-super-call
(super(GrandParent, self)...
)我想这是一个警告,如果您使用继承并且应该通过禁用pylint将其关闭,则不要错误地初始化类__mro__
中的直接类:
# pylint: disable=super-init-not-called
同时防止此类调用弄乱__mro__
链。
[您可以做的是允许在Child.__mro__
-> Child
-> Parent
(-> GrandParent
)中向上层叠object
项,同时在__init__
中按类引用跳过]]
class Parent(GrandParent): def __init__(self): super().__init__() if self.__class__ == Child: return
不会触发PyLint警告,并且显式允许正确的行为,并且不会跳过
__mro__
中的任何必需项。