访问类型为 Union 的变量的属性会引发错误

Accessing an attribute of a variable typed as Union throws an error

我对 Union 在 Python 静态类型中的用法有点困惑。

class A():
    foo: int = 10

class B():
    bar: str = 'hello'

def get_object() -> Union[A, B]:
    return B()

var = get_object()
var.bar

上面的代码片段returnserror: Item "A" of "Union[A, B]" has no attribute "bar"

文档状态

The interaction between Intersection and Union is complex but should be no surprise if you understand the interaction between intersections and unions of regular sets

这让我相信 Union[A, B] 类型的变量可以像 AB 类型一样使用,无需类型检查器抛出错误。这不正确吗?

如果是这样,我怎样才能实现模仿它的功能? (即来自 get_object 的值可以用作 AB 类型)

Union[A,B]表示值可以是或者类型A或者类型B..

而不是 意味着您可以根据自己的选择将值视为 AB。这正是使用交集类型。

当您有 Union[A,B] 时,您必须检查该值是否为 A,如果是,则像 A 一样处理它,或者如果它是 B,并像 B 一样处理它。优点是你知道它不会是其他类型 C,所以你有一个定义的类型列表来检查。但是你仍然需要通过某种方式进行检查。