如何在一个方法中调用同一个类中另一个方法的名称?就像这样:
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")
?另外,避免使用函数名。
例如:
>>> class C:
... def f1(self, arg1): print arg1
... def f2(self): return getattr(self, "f1")
...
>>> x=C()
>>> x.f2()(1)
1
def func2(self):
method = getattr(self, "func1")
method("arg")
但是你也应该检查它是否可调用。
if callable(method):
method("arg")
getattr
的理由 - 只需获取它即可。 - Ethan Furman