gpt4 book ai didi

python - Python 中有 "wildcard method"吗?

转载 作者:太空狗 更新时间:2023-10-30 01:57:44 27 4
gpt4 key购买 nike

我正在寻找一种方法来使用未在该类中定义但动态处理的类的方法。举个例子,我想实现的是从

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

可以在类中使用 aaabbb(以及其他)而不需要显式定义它们。对于上面的示例,这将是一个结构,它接收所使用的方法的名称(例如 aaa)并相应地格式化消息。

换句话说,“通配符方法”本身会处理其名称并根据名称执行条件操作。在伪代码中(复制上面的例子)

def *wildcard*(self, msg=""):
method = __name__which__was__used__to__call__me__
print("{msg} {method}".format(msg=msg, method=method))

这样的构造可能吗?

最佳答案

你可以重载类' __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")

结果:

hello aaa
hello bbb

关于python - Python 中有 "wildcard method"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36574812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com