2

我正在尝试getattr使用生成器在我的代码中使用函数

li=[]
m=[method for method in dir(li) if callable(getattr(li,method))]
print getattr(li,(str(i) for i in m))

错误

TypeError: getattr(): attribute name must be string

如果我在 i 上使用字符串强制,那么为什么会出现此错误?

另外,如果我使用代码

li=[]
m=[method for method in dir(li) if callable(getattr(li,method))]
for i in range(10):
    print getattr(li,str(m[i]))

然后没有错误

我是python新手,如果我犯了非常基本的错误,请原谅我,请有人详细说明错误。谢谢

编辑:同样的原则适用于这段代码(这是一个来自 Dive into python 的例子)。在这里,做了同样的事情,为什么没有错误?

def info(object, spacing=10, collapse=1):
    """Print methods and doc strings.

    Takes module, class, list, dictionary, or string."""
    methodList = [e for e in dir(object) if callable(getattr(object, e))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                     (method.ljust(spacing),
                      processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])
4

1 回答 1

4

好的,鉴于您的编辑,我已经更改了答案。您似乎期望生成器做一些与他们所做的不同的事情。

您不会将生成器传递给函数并让函数对生成器生成的每个项目起作用,而是循环生成器,然后在循环内执行所需的函数。

但是,在这里您不需要生成器表达式 - 只需遍历您的列表 - 例如:

for method in m:
    print(getattr(li, method))

如果您确实想使用生成器表达式,那么您可以在这里使用它而不是首先构造列表:

for method in (method for method in dir(li) if callable(getattr(li, method))):
    print(getattr(li, method))

尽管请注意,对于您在这里尝试做的事情,inspect模块可以帮助您避免很多您正在做的事情。

于 2012-05-27T15:16:01.590 回答