我的项目的设计方式是,如果用户想要扩展程序的功能,则可以通过自己编写一些函数来做到这一点,并且程序将自动为这些函数建立索引。
假设我在名为test()
的类中有一个函数Test
import inspect
class Test:
def test(self):
print('test')
for name, func in inspect.getmembers(Test):
if not name.startswith('__'): # For the exclusion of dunder functions
print(type(func))
exec(func.__code__) # I know that we can execute the code object of a function but this isn't working
exec(func) # And this ofcourse doesn't work
如何执行测试函数而无需像Test.test()
那样显式调用它。
答案 0 :(得分:1)
它需要类的实例,例如,您可以将其传递给一个或一个空dict:
import inspect
class Test:
def test(self):
print('test')
for name, func in inspect.getmembers(Test):
if not name.startswith('__'): # For the exclusion of dunder functions
print(type(func))
func({})
这里有一个live example
当您实际上需要从实例访问属性时,就会出现问题:
class Test:
def __init__(self):
self.foo = 'test'
def test(self):
print(self.foo)
与上面相同的代码将失败:
Traceback (most recent call last):
File "main.py", line 12, in <module>
func({})
File "main.py", line 7, in test
print(self.foo)
AttributeError: 'dict' object has no attribute 'foo'
因此,您仍然需要一个对象,该对象映射相同的属性并在该函数中调用所需的对象(通常是真实实例):
import inspect
class Test:
def __init__(self):
self.foo = 'test'
def test(self):
print(self.foo)
foo_instance = Test()
for name, func in inspect.getmembers(Test):
if not name.startswith('__'): # For the exclusion of dunder functions
print(type(func))
func(foo_instance)
为here