[英]Allow multiple data types in a dataclass variable
Is there a way to allow a dataclass variable to have one of multiple data types?有没有办法允许数据类变量具有多种数据类型之一? (And it should also work in Python 3.7) (它也应该适用于 Python 3.7)
@dataclass
class C:
index_range: tuple or str = "all"
I want index_range to have the default value string "all"
, but also the possibility to take a tuple as a value.我希望 index_range 具有默认值字符串"all"
,但也可以将元组作为值。 (Later in the function I define that "all"
means that all indices are used, but if a tuple is given only the elements between these numbers are used.) (稍后在函数中我定义"all"
意味着使用所有索引,但如果给出一个元组,则只使用这些数字之间的元素。)
Pylance always gives me the error that "all" is not a Tuple
. Pylance 总是给我"all" is not a Tuple
的错误。
Are also more than two types possible, like tuple or None or str?是否也可能有两种以上的类型,如元组或无或海峡?
You're looking for the typing.Union
:您正在寻找typing.Union
:
from typing import Union
@dataclass
class C:
index_range: Union[tuple, str] = "all"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.