2017-09-25 68 views
-3

我试图潜入蟒蛇和评​​估一些内置函数。 dir函数返回一个字符串列表,其中包含给定模块的所有属性的名称。 正因为如此,如果我运行下面的代码段,我得到一个空列表:列出所有模块的方法和属性作为对象列表

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

是否有其他功能或其他方式,我可以用dir(string)结合起来,获取对象的不是行的字符串列表?

我的目标是做这样的事情:

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

,而不是类似的例子在dive in python book

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

回答

3

这是因为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模块上的属性,你必须使用getattr(),或使用vars() function得到strings命名空间的字典:

>>> getattr(string, 'Formatter') 
<class 'string.Formatter'> 
>>> callable(getattr(string, 'Formatter')) 
True 
>>> [name for name in dir(string) if callable(getattr(string, name))] 
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', 'capwords'] 
>>> [name for name, obj in vars(string).items() if callable(obj)] 
['capwords', '_ChainMap', '_TemplateMetaclass', 'Template', 'Formatter'] 

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

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

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

我没有在此处链接,没有,但我没有考虑把它。我的道歉,我确实认为你已经阅读过。再次,评论是短暂的。如果你批评我的帖子,我不会触及评论(最多我会要求另一个mod看他们)。如果他们觉得我太快在这里清理,我会请另一位看看。事情是,如果我*不*清理我自己帖子下方的评论,当我看到它们已经过时时,那么它们可能需要很长时间才会*。我只是在这里自己收拾一下。 –

+0

谢谢,听起来都很合理。不需要另一个mod来看看。我认为这大部分是困扰我的琐事。 –

+0

我更新了问题,这是不好的公式。你有想法吗? –

-1

callable(x)检查是x是具有__call__()方法的对象。根据你的情况,这不,这就是为什么理解力返回一个空列表

相关问题