Python类型注释位于__

2024-10-01 22:39:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如何注释只有在__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)


Tags: 实例selfnonefooinitusedeftype
1条回答
网友
1楼 · 发布于 2024-10-01 22:39:11

我能想到的最简单的方法是将self.foo初始化为"",而不是{}。在

这意味着self.foo.upper()将可用,因此pylint没有理由抱怨。在

如果您不希望use_foo在调用get_foo(可能更好地称为set_foo)之前可用,您可以检查以确保填充了self.foo,或者保留一个布尔字段来说明它是否曾经运行过。在


如果您的类比字符串复杂一点,那么在使用self.foo之前,您必须快速检查一下。在

def use_foo(self):
    if self.foo is None:
        raise EnvironmentError("You haven't called get_foo!")
    self.foo.upper()

这不是一个非常干净的解决方案——我认为我们可以做得更好。在

让我们试着把这张支票外包给装修工

^{pr2}$

我还没有亲自尝试过pylint—但是如果pylint足够聪明,能够解决问题,那么在类方法上加上@ensure_foo会比到处都不检查干净得多。。。在

相关问题 更多 >

    热门问题