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])