Python |是否有方法执行inspect.getmembers()返回的函数
我的项目是这样设计的,如果用户想要扩展程序的功能,他可以自己编写一些函数,程序会自动索引这些函数 假设我在一个名为Python |是否有方法执行inspect.getmembers()返回的函数,python,python-3.x,Python,Python 3.x,我的项目是这样设计的,如果用户想要扩展程序的功能,他可以自己编写一些函数,程序会自动索引这些函数 假设我在一个名为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 functi
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.test()
它需要类的实例,您可以向它传递一个或一个空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({})
给你一个
当您实际需要从实例访问属性时,就会出现问题:
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)