python方法名 名称_按名称调用python方法

这里是一个使用Python装饰器的更通用的版本。你可以用短或长的名字打电话。我发现它在使用短和长子命令实现CLI时很有用。

巨蟒装饰师真是太棒了。Bruce Eckel(在爪哇思考)在这里描述了Python装饰者。

#!/usr/bin/env python2

from functools import wraps

class CommandInfo(object):

cmds = []

def __init__(self, shortname, longname, func):

self.shortname = shortname

self.longname = longname

self.func = func

class CommandDispatch(object):

def __init__(self, shortname, longname):

self.shortname = shortname

self.longname = longname

def __call__(self, func):

print("hello from CommandDispatch's __call__")

@wraps(func)

def wrapped_func(wself, *args, **kwargs):

print('hello from wrapped_func, args:{0}, kwargs: {1}'.format(args, kwargs))

func(wself, *args, **kwargs)

ci = CommandInfo

ci.cmds += [ci(shortname=self.shortname, longname=self.longname, func=func)]

return wrapped_func

@staticmethod

def func(name):

print('hello from CommandDispatch.func')

for ci in CommandInfo.cmds:

if ci.shortname == name or ci.longname == name:

return ci.func

raise RuntimeError('unknown command')

@CommandDispatch(shortname='co', longname='commit')

def commit(msg):

print('commit msg: {}'.format(msg))

commit('sample commit msg') # Normal call by function name

cd = CommandDispatch

short_f = cd.func(name='co') # Call by shortname

short_f('short sample commit msg')

long_f = cd.func(name='commit') # Call by longname

long_f('long sample commit msg')

class A(object):

@CommandDispatch(shortname='Aa', longname='classAmethoda')

def a(self, msg):

print('A.a called, msg: {}'.format(msg))

a = A()

short_fA = cd.func(name='Aa')

short_fA(a, 'short A.a msg')

long_fA = cd.func(name='classAmethoda')

long_fA(a, 'short A.a msg')

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值