gpt4 book ai didi

python - 如何获取函数的参数类型和返回类型?

转载 作者:太空宇宙 更新时间:2023-11-03 12:21:36 29 4
gpt4 key购买 nike

我正在尝试在 python 中实现强类型遗传编程。

是否有类似这些样本的东西?

def funcA(a,b):
return a + b
return_type(funcA)

output: <class 'Integer'>

def funcA(a,b):
return a + b
parameter_type(funcA)

output: [<class 'Integer'>,<class 'Integer'>]

更新:

我正在尝试生成 python 的表达式并避免无法像这样计算的东西:

funcA(20, funcA(True, "text"))

最佳答案

在Python这种动态类型语言中,运行时需要函数参数的类型信息。在3.3及之后的版本中,可以通过如下方式获取函数的类型:

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

sig = signature(foo)

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

str(sig.parameters['b'])
'b:int'

sig.parameters['b'].annotation
<class 'int'>

参见 https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object

关于python - 如何获取函数的参数类型和返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15200048/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com