sno*_*now 3 python types genetic-programming
我正在尝试在python中实现强类型的遗传编程.
有这样的样品吗?
def funcA(a,b):
return a + b
return_type(funcA)
output: <class 'Integer'>
Run Code Online (Sandbox Code Playgroud)
和
def funcA(a,b):
return a + b
parameter_type(funcA)
output: [<class 'Integer'>,<class 'Integer'>]
Run Code Online (Sandbox Code Playgroud)
更新:
我正在尝试生成python的表达式,并避免无法像这样评估的东西:
funcA(20, funcA(True, "text"))
Run Code Online (Sandbox Code Playgroud)
小智 13
你可以通过注释来检查:
>>> def func(a: str) -> int:
# code
>>> func.__annotations__["return"]
<class 'int'>
Run Code Online (Sandbox Code Playgroud)
与参数相同:
>>> func.__annotations__["a"]
<class 'str'>
Run Code Online (Sandbox Code Playgroud)
Bri*_* C. 10
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'>
Run Code Online (Sandbox Code Playgroud)
见https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object
Python 3引入了函数注释.他们自己不做任何事情,但你可以写自己的执法:
def strict(fun):
# inspect annotations and check types on call
@strict
def funcA(a: int, b: int) -> int:
return a + b
Run Code Online (Sandbox Code Playgroud)