import sys
def attrs_and_types(mod_name):
print('Attributes and their types for module {}:'.format(mod_name))
print()
for num , attr in enumerate(dir(eval(mod_name))):
print("{idx}: {nam:30} {typ}".format(
idx=str(num + 1).rjust(4),
nam=(mod_name + '.' + attr).ljust(30),
typ=type(eval(mod_name + '.' + attr))))
attrs_and_types(sys.__name__)
谁能帮我解决这两行问题吗?
for num, attr in enumerate(dir(eval(mod_name))):
attrs_and_types(sys.__name__)
我不明白为什么 sys.__name__
作为参数传递给函数。它应该是模块的名称。为什么 .__name__
添加到 sys
中?
在 for
循环中 num, attr
正在检查:
enumerate(dir(eval(mod_name)))
这是什么?它是一个内存位置吗?
最佳答案
Why is
.__name__
added to sys?
每个模块都有一个附加有其名称的 __name__
属性。事情就是这样。
What is this? Is it a memory location?
不,作者决定使用 eval
(出于某种原因)来评估传递的字符串 (sys.__name__
) 并返回模块对象。我不明白他为什么决定这样做,允许函数接收一个 arg 然后将其传递给 eval
是非常危险的,所以不要这样做。
更好的实现(不使用 inspect
模块)如下所示:
import sys
def attrs_and_types(mod):
name = mod.__name__
print('Attributes and their types for module {}:\n'.format(name))
fmt = "{idx}: {nam:30} {typ}"
for num , attr in enumerate(dir(sys)):
s = fmt.format(
idx=str(num + 1).rjust(4),
nam=(name + '.' + attr).ljust(30),
typ=type(attr)
)
print(s)
attrs_and_types(sys)
如果您只是直接传递模块对象,则不需要eval
。即使您确实传递了 __name__
,您仍然可以通过 sys.modules
以更安全的方式取回模块。
关于python - 获取Python模块属性的名称和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207624/