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

Kal*_*lly 3 python types

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

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

这会导致类型错误

TypeError: unsupported operand type(s) for |: 'type' and 'type'
Run Code Online (Sandbox Code Playgroud)

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

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

Tom*_*sen 7

是的,在输入时这是通过以下方式完成的Union

from typing import Union

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

请注意,正如您可以从文档中读到的那样,这可以int | float在 Python 3.10 及以上版本中实现。由于大多数用户尚未使用 Python 3.10,因此实际上人们仍然倾向于使用Union[int, float]. 但是,int | float如果您不关心支持 Python 3.10 以下的版本,则首选。