PyLint W0231用祖父母的__init__进行的超级初始化未调用

问题描述 投票:1回答:1

我创建了一个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
        ...  
python inheritance pylint
1个回答
0
投票

您可以尝试多种方式,例如:

GrandParent.__init__(self)
super().super().__init__(self)
super(GrandParent, self).__init__()

但是错误仍然存​​在:

  • super-init-not-called
  • bad-super-callsuper(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__中的任何必需项。

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