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

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

例子:

>>> 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数据结构,而不仅仅是一个string:

>>> 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'

或者,您可以使用函数属性来validation调用的值:

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:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值