获取python中的参数类型

leo*_*eon 6 python types arguments

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

Ant*_*iez 10

formatargspec自 3.5 版本起已弃用。更喜欢signature

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

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b:int, **kwargs)'
Run Code Online (Sandbox Code Playgroud)

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


Ven*_*nky 6

在 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>):
Run Code Online (Sandbox Code Playgroud)

然后你可以使用formatargspec(*getfullargspec(f))which 返回一个很好的散列,如下所示:

(a: int, b: float)
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 5

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

如果您的意思是从函数外部,则不:可以使用任何类型的参数调用该函数——某些此类调用会产生错误,但无法先验地知道它们将是哪些。

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


Joh*_*ooy -2

有一个函数叫做type().
这是文档

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

>>> 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'>
Run Code Online (Sandbox Code Playgroud)

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