WoJ*_*WoJ 4 python methods class
我正在寻找一种方法来使用一个类的方法,该方法没有在该类中定义,但动态处理.举个例子,我想要实现的是从中走出来
class Hello:
def aaa(self, msg=""):
print("{msg} aaa".format(msg=msg))
def bbb(self, msg=""):
print("{msg} bbb".format(msg=msg))
if __name__ == "__main__":
h = Hello()
h.aaa("hello")
h.bbb("hello")
# hello aaa
# hello bbb
Run Code Online (Sandbox Code Playgroud)
在类中使用aaa和bbb(和其他)的可能性,而无需明确定义它们.对于上面的示例,它将是一个接收所用方法名称(aaa例如)并相应地格式化消息的构造.
换句话说,一个"通配符方法",它本身将处理其名称并根据名称执行条件操作.在伪代码中(复制上面的例子)
def *wildcard*(self, msg=""):
method = __name__which__was__used__to__call__me__
print("{msg} {method}".format(msg=msg, method=method))
Run Code Online (Sandbox Code Playgroud)
这样的建筑可能吗?
Kev*_*vin 11
你可以重载类的__getattr__方法:
class Hello:
def __getattr__(self, name):
def f(msg=""):
print("{} {}".format(msg, name))
return f
if __name__ == "__main__":
h = Hello()
h.aaa("hello")
h.bbb("hello")
Run Code Online (Sandbox Code Playgroud)
结果:
hello aaa
hello bbb
Run Code Online (Sandbox Code Playgroud)