有什么办法可以获取模块的所有功能,以便我可以调用它们?
如果我说:
m.py:
__all__ = ['Bark']
def Bark():
print('Bark')
main.py:
import m
for f in m.__all__:
print(m.f)
我收到AttributeError:模块'm'没有属性'f'。
如何打印
功能树皮是否位于0x000000?
如果您有包含属性名称的字符串,请使用getattr
获取属性:
getattr
print(getattr(m, f))
现在,您是否真的想知道该项目是否是一个函数,或者您想知道它是否可调用?那是两件事。您可以使用如上所示的import m
for name in dir(m):
item = getattr(m, name)
print(f"{name} is {type(item)}")
if isinstance(item, types.FunctionType):
print(f"{name} is a function!")
# can call function thusly:
# item(args...)
,但有关更多信息,请参见isinstance(item, types.FunctionType)
。