gpt4 book ai didi

__init__ 中的 Python 键入注释

转载 作者:太空宇宙 更新时间:2023-11-04 04:35:27 25 4
gpt4 key购买 nike

如何注解在__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".

如何让 PyLint 开心? (不禁用 T484)

最佳答案

我能想到的最简单的方法是简单地将 self.foo 初始化为 "" 而不是 None

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

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


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

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

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

让我们尝试将此检查外包给装饰器;

def ensure_foo(func):
def inner_func(self, *args, **kwargs):
if self.foo is None:
raise EnvironmentError("You haven't called get_foo!")
func(self, *args, **kwargs)
return inner_func

我还没有亲自用 pylint 尝试过这个 - 但如果 pylint 足够聪明,可以弄清楚发生了什么,那么在你的类方法之上添加 @ensure_foo 会比无处不检查......

关于__init__ 中的 Python 键入注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51834649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com