在python中,假设我有一个字符串,其中包含我知道特定对象将具有的类函数的名称,如何调用它?
那是:
obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?
Run Code Online (Sandbox Code Playgroud)
Ada*_*erg 62
使用"getattr":http://docs.python.org/library/functions.html?highlight = getattr #getattr
obj = MyClass()
try:
func = getattr(obj, "dostuff")
func()
except AttributeError:
print "dostuff not found"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33724 次 |
| 最近记录: |