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

OK、あなたの編集を踏まえて、答えを変更しました。ジェネレーターが行うこととは異なることを期待しているようです。

ジェネレーターを関数に渡さず、ジェネレーターによって生成された各アイテムで関数を機能させます。ジェネレーターをループしてから、ループ内で必要な関数を実行します。

ただし、ここではジェネレーター式は必要ありません。リストをループするだけです。例:

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 に答える