我有一个超类,它使用子类中的一些属性。但除非我在超类中也定义了属性,否则linter就会抛出错误。
解决这个问题的蟒蛇方法是什么?
# 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这是一个“超类”,所以在独立实例中作为一个错误是足够公平的。
但我更喜欢干净的线条,pythonic式的代码,而不是仅仅为了让linter闭嘴而写一些特别的东西。
发布于 2021-06-07 12:14:33
在您的示例中,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>", line 1, in <module>
File "<stdin>", line 3, in foo
AttributeError: 'C' object has no attribute 'bar'如果基类不打算直接实例化,请考虑将其设置为Abstract Base Class
https://stackoverflow.com/questions/67865823
复制相似问题