微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python linting 和子类属性

如何解决python linting 和子类属性

我有一个超类,它使用子类的一些属性。 但除非我在超类中定义属性,否则 linter 会抛出错误

解决这个问题的 Pythonic 方法是什么?

# parent
class DigItem:
    def fetch_bq(self):
        query = f'''select * from {self.table_id}'''

# subclass
class ChatLog(DigItem):

    def __init__(self,set_name):
        super().__init__(set_name)
        self.table_id = biglib.make_table_id('chat_logs')

以上代码错误

Instance of 'DigItem' has no 'table_id' memberpylint(no-member)

现在,我可以将属性添加到超类中,但这非常多余,而且还有覆盖子类的风险

class DigItem:
    def __init__(self,set_name):
        self.table_id = None # set by child

这归结于 linter 无法知道 AOT 这是一个“超类”,因此在独立实例中作为错误是足够公平的。

但我更喜欢干净的 linting、pythonic 代码,而不是为了关闭 linter 而编写特殊的hacky 东西。

解决方法

在您的示例中,DigItem 根本没有 __init__(因此它将是 object),因此将参数传递给 super().__init__() 将失败

>>> class A: pass
...
>>> class B(A):
...   def __init__(self):
...     super().__init__("something")
...
>>> B()
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
  File "<stdin>",line 3,in __init__
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

此外,您应该(必须)在父级中创建缺少的属性,以便它在方法中有意义地使用它(否则不同的继承类将无法使用该方法)

>>> class A:
...   def foo(self):
...     return self.bar
...
>>> class B(A):
...   def __init__(self):
...     self.bar = "baz"
...
>>> class C(A): pass  # NOTE .bar is never defined!
...
>>> C().foo()
Traceback (most recent call last):
  File "<stdin>",in foo
AttributeError: 'C' object has no attribute 'bar'

如果基类不打算直接实例化,请考虑将其设为 Abstract Base Class

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。