问题
I have a generator defined like this:
def lengths(x):
for k, v in x.items():
yield v['time_length']
And it works, calling it with
for i in lengths(x):
print i
produces:
3600
1200
3600
300
which are the correct numbers.
However, when I call it like so:
somefun(lengths(x))
where somefun()
is defined as:
def somefun(lengths):
for length in lengths(): # <--- ERROR HERE
if not is_blahblah(length): return False
I get this error message:
TypeError: 'generator' object is not callable
What am I misunderstanding?
回答1:
You don't need to call your generator, remove the ()
brackets.
You are probably confused by the fact that you use the same name for the variable inside the function as the name of the generator; the following will work too:
def somefun(lengen):
for length in lengen:
if not is_blahblah(length): return False
A parameter passed to the somefun
function is then bound to the local lengen
variable instead of lengths
, to make it clear that that local variable is not the same thing as the lengths()
function you defined elsewhere.
来源:https://stackoverflow.com/questions/12074726/typeerror-generator-object-is-not-callable