質問

I am trying to use getattr function in my code using generator

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

Error:

TypeError: getattr(): attribute name must be string

if I am using string coercion on i, then why this error shows up?

Also,if I use the code

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

Then there is no error

I am new to python, forgive me if i am making very elementary mistake, please can someone elaborate on the error. Thanks

Edit: The same principle works for this code (it is an example from Dive into python). Here,the same thing is done then why there is no error?

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])
役に立ちましたか?

解決

OK, given your edit I have changed my answer. You appear to be expecting generators to do something different to what they do.

You don't pass a generator to a function and have the function work on each item produced by the generator, you loop over a generator and then perform the functions you want inside the loop.

However, here you don't need a generator expression - just loop over your list - E.g:

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

If you did want to use a generator expression, then you could use it here instead of constructing the list in the first place:

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

Although note that, for what you are trying to do here, the inspect module can help avoid a lot of what you are doing.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top