【问题标题】:In Python, is it possible to restrict the type of a function parameter to two possible types? [duplicate]在 Python 中,是否可以将函数参数的类型限制为两种可能的类型? [复制]
【发布时间】:2021-03-06 19:39:12
【问题描述】:

我尝试将“参数”类型限制为 int 或列表,如下面的函数“f”。但是,Pycharm 没有在 f("weewfwef") 行显示有关错误参数类型的警告,这意味着 this (parameter : [int, list]) 不正确。

在 Python 中,是否可以将 python 函数参数的类型限制为两种可能的类型?

def f(parameter : [int, list]):
    if len(str(parameter)) <= 3:
        return 3
    else:
        return [1]

if __name__ == '__main__':
    f("weewfwef")

【问题讨论】:

    标签: python


    【解决方案1】:

    您要查找的术语是union type

    from typing import Union
    
    def f(parameter: Union[int, list]):
      ...
    

    Union 不限于两种类型。如果您曾经有一个值是几种已知类型之一,但您不一定知道是哪一种,您可以使用Union[...] 来封装该信息。

    【讨论】:

      【解决方案2】:

      试试typing.Union

      from typing import Union
      def f(parameter : Union[int,list]):
          if len(str(parameter)) <= 3:
              return 3
          else:
              return [1]
      

      【讨论】:

        【解决方案3】:

        在python中,没有这么严格的类型检查,这就是为什么它遵循鸭子类型https://realpython.com/lessons/duck-typing/

        def f(parameter : [int, list]):
            if not(type(parameter) in [list, int]):
                raise ValueError("Invalid Input type")
            if len(str(parameter)) <= 3:
                return 3
            else:
                return [1]
        

        【讨论】:

          【解决方案4】:
          def f(parameter : [int, list]):
              if type(parameter) == (int or list):
                  if len(str(parameter)) <= 3:
                      return 3
                  else:
                      return [1]
              else:
                  raise ValueError # You can use other error if you want to
          
          if __name__ == '__main__':
              print(f("weewfwef"))
          

          使用type()检查它的类型并使用if语句并引发错误

          【讨论】:

            猜你喜欢
            • 2011-11-12
            • 2019-03-14
            • 1970-01-01
            • 2021-12-15
            • 2016-01-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-02-04
            相关资源
            最近更新 更多