如何创建一个函数,其参数接受2个或更多的数据类型。我有一个产品类,如下所示
class Product:
def __init__(self, name: str, price: int | float)
self.product = {'name': name, 'price': price)这将生成一个TypeError
TypeError: unsupported operand type(s) for |: 'type' and 'type'然后我尝试使用or操作符,但它只选择type int
如何确保它既接受int,又接受float。
发布于 2022-01-26 12:35:18
是的,在输入时,这是用Union完成的。
from typing import Union
class Product:
def __init__(self, name: str, price: Union[int, float])
self.product = {'name': name, 'price': price)注意,正如您可以从文档中看到的那样,这在int | float中是可能的,但只能从Python3.10版本开始。由于大多数用户还没有使用Python3.10,实际上人们仍然倾向于使用Union[int, float]。但是,如果您不关心支持Python3.10以下的版本,则最好使用int | float。
https://stackoverflow.com/questions/70863481
复制相似问题