gettattr,python 中的“属性必须是字符串”错误

sum*_*000 2 python typeerror getattr

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

li=[]
m=[method for method in dir(li) if callable(getattr(li,method))]
print getattr(li,(str(i) for i in m))
Run Code Online (Sandbox Code Playgroud)

错误

TypeError: getattr(): attribute name must be string
Run Code Online (Sandbox Code Playgroud)

如果我在 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]))
Run Code Online (Sandbox Code Playgroud)

然后就没有错误了

我是 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])
Run Code Online (Sandbox Code Playgroud)

Gar*_*tty 5

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

您不需要将生成器传递给函数并让该函数对生成器生成的每个项目起作用,您可以循环生成器,然后在循环内执行您想要的函数。

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

for method in m:
    print(getattr(li, method))
Run Code Online (Sandbox Code Playgroud)

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

for method in (method for method in dir(li) if callable(getattr(li, method))):
    print(getattr(li, method))
Run Code Online (Sandbox Code Playgroud)

尽管请注意,对于您在此处尝试执行的操作,inspect模块可以帮助避免您正在执行的许多操作。