欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python中的def是什么意思啊_在Python函数定义中-是什么意思?

发布时间:2024/1/18 python 43 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python中的def是什么意思啊_在Python函数定义中-是什么意思? 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

这些是PEP 3107中介绍的函数注释。具体来说,->标记返回函数注释。

示例:>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules':

... return 1/2*m*v**2

...

>>> kinetic_energy.__annotations__

{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

注释是字典,因此您可以执行以下操作:>>> '{:,} {}'.format(kinetic_energy(20,3000),

kinetic_energy.__annotations__['return'])

'90,000,000.0 Joules'

您还可以使用python数据结构,而不仅仅是字符串:>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'}

>>> def f()->rd:

... pass

>>> f.__annotations__['return']['type']

>>> f.__annotations__['return']['units']

'Joules'

>>> f.__annotations__['return']['docstring']

'Given mass and velocity returns kinetic energy in Joules'

或者,可以使用函数属性验证调用的值:def validate(func, locals):

for var, test in func.__annotations__.items():

value = locals[var]

try:

pr=test.__name__+': '+test.__docstring__

except AttributeError:

pr=test.__name__

msg = '{}=={}; Test: {}'.format(var, value, pr)

assert test(value), msg

def between(lo, hi):

def _between(x):

return lo <= x <= hi

_between.__docstring__='must be between {} and {}'.format(lo,hi)

return _between

def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):

validate(f, locals())

print(x,y)

印刷品>>> f(2,2)

AssertionError: x==2; Test: _between: must be between 3 and 10

>>> f(3,2.1)

AssertionError: y==2.1; Test:

总结

以上是生活随笔为你收集整理的python中的def是什么意思啊_在Python函数定义中-是什么意思?的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。