【问题标题】:Python3: pass type as function parameterPython3:将类型作为函数参数传递
【发布时间】:2022-10-06 02:45:57
【问题描述】:

如何在 python 中将intstr 作为函数参数传递?

例子:

def fn(type:<arg typing here>):
    # do something

output = fn(type=int)

来自django commands 的示例 2:

parser.add_argument(
        \'years\', type=int, help=\"Determines how many years of fake data to generate.\")

    标签: python-3.x python-typing


    【解决方案1】:

    除了打字声明,你的代码应该已经可以工作了。要输入参数,您可以使用typing.Type

    from typing import Type
    
    def fn(type: Type):
        # do something
    

    但是,您可能不想使用内置名称 type 作为参数的名称。有些人可能更喜欢这样的东西:

    from typing import Type
    
    def fn(typ: Type):
        # do something
    

    【讨论】:

      【解决方案2】:

      您不需要指定类型,但您可以使用 arg: type 来表示类型,如下所示:

      def foo(a: str, b: int):
          # stuff
          return a, b
      

      请注意,这不会阻止用户执行foo(a=1, b="2") 之类的操作……也就是说,它不会在类型不匹配的情况下引发错误。

      【讨论】:

      • 我需要将int | str 类传递为parameter value,而不是parameter type(如果有意义的话),我可以使用Union | Literal | Any 键入大多数变量,但我无法为此目的使用它们。
      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多