Sha*_*kan 8 python variables methods function
如何通过从被调用方法在同一类中的另一个方法给出其名称来执行方法?像这样:
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
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
怎么样getattr(self, "func1")?另外,请避免使用名称功能
例如:
>>> class C:
... def f1(self, arg1): print arg1
... def f2(self): return getattr(self, "f1")
...
>>> x=C()
>>> x.f2()(1)
1
Run Code Online (Sandbox Code Playgroud)
您应该从类中获取属性,而不是模块.
def func2(self):
method = getattr(self, "func1")
method("arg")
Run Code Online (Sandbox Code Playgroud)
但是你也应该检查它是否可以调用.
if callable(method):
method("arg")
Run Code Online (Sandbox Code Playgroud)
这样可以避免调用你不希望得到的东西.如果它不可调用,您可能希望在此处引发自己的异常.