如何注释只有在__init__
之后才可用的实例变量的类型?我想按POLS列出__init__
中的所有实例属性。在
MWE:
class MyClass(object):
def __init__(self):
self.foo :Union[CustomClass, None] = None
def set_foo(self):
self.foo = CustomClass()
def use_foo(self):
self.foo.do_something()
在__init__
中,如果我只是将foo注释为self.foo: CustomClass = None
,Pylint会抱怨:
T484: Incompatible types in assignment (expression has type None, variable has type "CustomClass").
但是,如果我将foo
注释为self.foo: Union[CustomClass, None] = None
(如上面的MWE所示),那么PyLint将在use_foo
函数中抱怨:
T484: "None" has no attribute "do_something".
我怎样才能让皮林高兴?(不禁用T484)
我能想到的最简单的方法是将}。在
self.foo
初始化为""
,而不是{这意味着
self.foo.upper()
将可用,因此pylint没有理由抱怨。在如果您不希望
use_foo
在调用get_foo
(可能更好地称为set_foo
)之前可用,您可以检查以确保填充了self.foo
,或者保留一个布尔字段来说明它是否曾经运行过。在如果您的类比字符串复杂一点,那么在使用
self.foo
之前,您必须快速检查一下。在这不是一个非常干净的解决方案——我认为我们可以做得更好。在
让我们试着把这张支票外包给装修工
^{pr2}$我还没有亲自尝试过pylint—但是如果pylint足够聪明,能够解决问题,那么在类方法上加上
@ensure_foo
会比到处都不检查干净得多。。。在相关问题 更多 >
编程相关推荐