键入可能不存在的属性的提示

问题描述 投票:0回答:1

如何对 Python 中对象上可能不存在的属性进行类型提示? 例如:

class X:
    attr: int  # either int or doesn't exist - what do I put here?
python attributes python-typing
1个回答
0
投票

只需使用与

Optional
模块捆绑在一起的
Typing
类即可。

这是它的文档。

以下是我们如何将其应用到您的示例案例:

from typing import Optional

class X:
    attr: Optional[int]

编辑:由于您只需要检查变量是否已创建以及属性是否存在于对象中,因此有两种方法可以做到这一点:

使用 Python 中的 Locals/Globals 内置函数:

if variable_name in locals():
    print(f"Variable exists locally.")

if variable_name in globals():
    print(f"Variable exists globally.")

或者,最简单的方法,只需执行 Try/Exception:

try:
    x
    some_operation(x)
except NameError:
    some_fallback_operation(  )

我链接了 Python 中有关 Globals/Locals 函数的文档,以及 O'Reily Cookbook 中解释 Try/Exception 方法的主题。

编辑2:添加了另一个内置函数来处理与我从globals()发送的同一文档链接中的对象/类 - getattr()方法。

class MyClass:
    def __init__(self):
        self.attribute = "Whatever"


obj = MyClass()

# Try/Catch to try accessing a non-existing variable.
try:
    whatever = getattr(obj, "attribute")
    print(whatever)
except AttributeError:
    print("Error - There is no variable.")

我希望这对您有帮助。 :)

© www.soinside.com 2019 - 2024. All rights reserved.