【问题标题】:Set attribute to be multiple types in dataclass - Python 3.9.x [duplicate]在数据类中将属性设置为多种类型 - Python 3.9.x [重复]
【发布时间】:2022-01-17 03:46:11
【问题描述】:

我正在使用dataclass 装饰器。

对于我的一个变量,我希望它是 strint 类型

from dataclasses import dataclass

@dataclass
class Foo:
    test_var: str
    # test_var: int

    def get_example(self):
        return type(self.test_var)

我希望test_var 在构造Foo 对象时成为strint;如何为我的类的属性指定两种类型?

【问题讨论】:

  • 类似test_var: typing.Union[str, int]?
  • 看起来它使用了PEP 526注解。一个相关问题here

标签: python object oop


【解决方案1】:

你正在寻找Union:

联合类型; Union[X, Y] 表示 X 或 Y。

from dataclasses import dataclass

@dataclass
class Foo:
    test_var: Union[str, int]

    def get_example(self):
        return type(self.test_var)

请注意,在 Python 3.10 中,您可以使用 X | Y 语法,它等效于 Union[X, Y](参见 the docs)。

【讨论】:

  • 请注意,X | Y 语法也可以在 Python 3.7+ 中使用 __future__ 导入来支持。
猜你喜欢
  • 2015-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多