将所有模块方法和属性作为对象列表列出

2024-05-18 23:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图深入研究python并评估一些内置函数。 dir函数返回一个字符串列表,其中包含给定模块的所有属性的名称。 因此,如果我运行以下代码段,就会得到一个空列表:

import string
[x for x in dir(string) if callable(x) ]

是否有其他函数或其他方法可以与dir(string)结合使用,以获得对象列表而不是行字符串?在

我的目标是:

^{pr2}$

而不是dive in python book中的例子

 methodList = [method for method in dir(object) if callable(getattr(object, method))]

Tags: 模块函数字符串in列表forstringif
2条回答

callable(x)checks是x是一个具有__call__()方法的对象。在你的情况下,它没有,这就是为什么理解返回一个空列表

这是因为dir()返回字符串的列表

>>> import string
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

字符串值不可调用;这些不是实际的属性值,而是名称。在

如果要将这些名称作为属性测试在string模块上,则必须使用^{},或使用^{} function将{}命名空间作为字典:

^{pr2}$

这里的顺序不同,因为dictionaries are unordereddir()总是对返回值进行排序。对于模块dir(module)只返回sorted(vars(module))。在

如果需要可调用对象本身而不是名称,只需过滤vars()字典的

[obj for obj in vars(string).values() if callable(obj)]

相关问题 更多 >

    热门问题