python - 获取Python模块属性的名称和类型

标签 python python-3.x

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/

相关文章:

Python从日期时间结果中获取总秒数偶尔会出现错误

python - 为什么这个循环只取第一个值?

python - Python 3 中更快的 for 循环

python - 如何使 pandas.read_sql() 不将所有 header 转换为小写

python :按键错误 'shift'

javascript - 在不根据 Django 管理站点检查用户的情况下登录 Django 网站

python-3.x - RuntimeError : Given groups=3, 大小为 12 64 3 768 的权重,预期输入 [32, 12, 30, 768] 有 192 个 channel ,但得到了 12 个 channel

Python:从 Notepad++ 运行代码到 Python 控制台

python - Surface.scroll() 是在 Pygame 中实现可移动 2D 视点的正确方法吗?

python3.3在linux中找不到libpython3.3m.so(pip-3.3)