gpt4 book ai didi

python变量方法名

转载 作者:太空狗 更新时间:2023-10-29 20:46:24 25 4
gpt4 key购买 nike

如何从与被调用方法在同一个类中的另一个方法通过给出方法的名称来执行方法?像这样:

class Class1:
def __init__(self):
pass
def func1(self, arg1):
# some code
def func2(self):
function = getattr(sys.modules[__name__], "func1") # apparently this does not work

有什么建议吗?

最佳答案

getattr(self, "func1") 怎么样?另外,避免使用 name 函数

例如:

>>> class C:
... def f1(self, arg1): print arg1
... def f2(self): return getattr(self, "f1")
...
>>> x=C()
>>> x.f2()(1)
1

关于python变量方法名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7129736/

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