是否可以使函数参数接受 2 种或更多类型?

Is it possible to make a function parameter accept 2 or more type?

如何创建一个参数接受 2 种或更多数据类型的函数。我有一个产品 class 如下

class Product:
      def __init__(self, name: str, price: int | float)
          self.product = {'name': name, 'price': price)

这会导致类型错误

TypeError: unsupported operand type(s) for |: 'type' and 'type'

然后我尝试使用 or 运算符,但它只接收 type int

我怎样才能确保它接受 int 和 float

是的,在输入时使用 Union:

from typing import Union

class Product:
    def __init__(self, name: str, price: Union[int, float])
        self.product = {'name': name, 'price': price)

请注意,您可以从文档中了解到,int | float 可以实现这一点,但只能从 Python 3.10 版开始。由于大多数用户尚未使用 Python 3.10,实际上人们仍然倾向于使用 Union[int, float]。 但是,如果您不关心支持低于 Python 3.10.

的版本,则首选 int | float