示例代码文件:
MyCode.py
def DoSomething(data):
# data is a string
# find a function in the same scope as this one that has the name contained
# in "data"
try:
func = getattr(self,data) # this is wrong
except AttributeError:
print "Couldn't find function %s." % data
return
# execute the function
func()
def AFunction():
print "You found a function!"
def Add():
print "1 + 1 = %d." % ( (1+1) )
def test():
# unit test
DoSomething("AFunction")
--------
test.py
import MyCode
# Try executing some functions
MyCode.DoSomething("AFunction") # should print You found a function!
MyCode.DoSomething("Add") # should print 1+1=2.
MyCode.DoSomething("IDoNotExist") # should run the exception handler
# Try executing a function from inside the module
MyCode.test() # should print You found a function!
Run Code Online (Sandbox Code Playgroud)
如果我正在处理一个类对象,该getattr
语句最终将检索对类中与所提供的名称匹配的函数的引用。然后,如图所示,我可以直接从变量名执行该函数。
但是,由于这些函数不在类中,而是在模块/文件级别,因此getattr
在 self 上使用将不起作用,因为我们没有self
对类实例的引用。
我的问题是:实际上是否有必要将此函数及其所有支持函数包装在一个类中并实例化该类才能具有此功能?或者,是否有其他方法可以使用getattr
,以便我可以访问在文件级别定义的函数。
请注意这两个用例:在文件本身内,“测试”函数需要调用这些函数,但也需要从外部导入运行任意其他函数的函数可能需要运行。
感谢建议。
谢谢!
import sys
current_module = sys.modules[__name__]
getattr(current_module, 'AFunction')
Run Code Online (Sandbox Code Playgroud)
不过,用类包装所有内容会更安全。
归档时间: |
|
查看次数: |
3155 次 |
最近记录: |