【问题标题】:Get types of arguments in python获取python中的参数类型
【发布时间】:2010-02-09 06:11:07
【问题描述】:

我正在学习 python。我喜欢使用 help() 或 interinspect.getargspec 来获取 shell 中函数的信息。但是无论如何我可以获得函数的参数/返回类型。

【问题讨论】:

标签: python types arguments


【解决方案1】:

formatargspec 自 3.5 版起已弃用。首选signature

>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b:int, **kwargs)'

注意:某些可调用对象在某些 Python 实现中可能无法自省。例如,在 CPython 中,一些用 C 定义的内置函数不提供有关其参数的元数据。

【讨论】:

    【解决方案2】:

    在 3.4.2 文档 https://docs.python.org/3/library/inspect.html 中,提到了您确切需要的内容(即获取函数的参数类型)。

    您首先需要像这样定义您的函数:

    def f(a: int, b: float, c: dict, d: list, <and so on depending on number of parameters and their types>):
    

    然后你可以使用formatargspec(*getfullargspec(f)),它会返回一个像这样的漂亮哈希:

    (a: int, b: float)
    

    【讨论】:

    • 这个问题来自 2010 年......远在 3.4.2 存在之前。我会考虑删除这个答案。
    • 已弃用,请改用签名,见下文。
    【解决方案3】:

    如果你的意思是在函数的某个调用期间,函数本身可以通过在每个参数上调用type 来获取其参数的类型(并且肯定会知道它返回的类型)。

    如果你的意思是从函数外部,不可以:可以使用任何类型的参数调用函数——一些这样的调用会产生错误,但没有办法先验地知道它们会是哪些。

    参数可以在 Python 3 中选择性地进行修饰,这种修饰的一种可能用途是表达有关参数类型(和/或对它们的其他约束)的一些信息,但是语言和标准库没有提供关于如何这样的指导可能会用到装饰。您不妨采用一种标准,从而在函数的文档字符串中以结构化方式表达此类约束,这将具有适用于任何 Python 版本的优势。

    【讨论】:

      【解决方案4】:

      有一个函数叫type()
      Here are the docs

      你无法提前知道函数会返回什么类型

      >>> import random
      >>> def f():
      ...  c=random.choice("IFSN")
      ...  if c=="I":
      ...   return 1
      ...  elif c=="F":
      ...   return 1.0
      ...  elif c=="S":
      ...   return '1'
      ...  return None
      ... 
      >>> type(f())
      <type 'float'>
      >>> type(f())
      <type 'NoneType'>
      >>> type(f())
      <type 'float'>
      >>> type(f())
      <type 'int'>
      >>> type(f())
      <type 'str'>
      >>> type(f())
      <type 'float'>
      >>> type(f())
      <type 'float'>
      >>> type(f())
      <type 'NoneType'>
      >>> type(f())
      <type 'str'>
      

      从函数中只返回一种类型的对象通常是一种很好的做法,但 Python 不会强迫你这样做

      【讨论】:

        猜你喜欢
        • 2013-08-15
        • 2021-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-03
        • 1970-01-01
        • 2015-12-04
        • 1970-01-01
        相关资源
        最近更新 更多