我有一个暴露两种方法的类。这些方法实际上是视觉语法糖,它们最终指向行为不同的相同代码,具体取决于它接收的有效负载:
class Action:
def on(self):
self.action(1)
def off(self):
self.action(2)
def action(self, payload):
# a long function which does many things and uses the payload from on() and off()
print(payload)
a = Action()
a.on()
a.off()
有没有办法定义on()
和off()
,以便它们指向相同的代码(action()
中的代码),的行为会有所不同,具体取决于名称被称为?
我当然可以通过电话中的动作:
class Action:
def action(self, what):
payload = 1 if what == 'on' else 0
# a long function which does many things and uses the payload from on() and off()
print(payload)
a = Action()
a.action('on')
a.action('off')
但我希望保持类方法的开/关结构。
答案 0 :(得分:1)
这与您的第一个示例非常相似,但您在寻找functools.partial吗?
您可以使用它自动将某些参数设置为函数,返回值也是函数对象。使用它,你可以这样做:
import functools
class Abc(object):
def action(self, payload):
print(payload)
def __init__(self):
self.off = functools.partial(self.action, payload=1)
self.on = functools.partial(self.action, payload=2)
然后,您拥有action
,on
和off
功能,所有功能都按预期工作:
foo = Abc()
foo.on()
>>> 2
foo.off()
>>> 1
foo.action(9)
>>> 9
使用partial
是一种语义上更强的方式来说这是用于调用另一个函数的语法糖。诸如def on(self): ...
之类的函数声明可以是任何东西,而self.on = functools.partial(action,...)
明确指出你将一个函数绑定到另一个函数。
答案 1 :(得分:0)
def _action_maker(payload):
def _action(self):
return self.action(payload)
return _action
class Action:
on = _action_maker(1)
off = _action_maker(2)
def action(self, payload):
# a long function which does many things and uses the payload from on() and off()
print(payload)
但就我个人而言,我不喜欢这样,因为我的编辑不理解它,并给我错误的警告。
答案 2 :(得分:-1)
inspect
import inspect
class Action:
def on(self):
self.action(1)
def off(self):
self.action(2)
def action(self, payload):
# a long function which does many things and uses the payload from on() and off()
currentframe = inspect.currentframe()
callername = inspect.getouterframes(currentframe, 2)[1][3]
if callername =='on':
print('on')
elif callername == 'off':
print('off')
a = Action()
a.on() #on
a.off() #off
class Action:
def on(self):
self.action(1,'on')
def off(self):
self.action(2, 'off')
def action(self, payload, callername):
# a long function which does many things and uses the payload from on() and off()
if callername =='on':
print('on')
elif callername == 'off':
print('off')
a = Action()
a.on() #on
a.off() #off