TypeError:“发电机"对象不可调用 [英] TypeError: 'generator' object is not callable

查看:64
本文介绍了TypeError:“发电机"对象不可调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的生成器:

I have a generator defined like this:

def lengths(x):
    for k, v in x.items():
        yield v['time_length']

它起作用了,用

for i in lengths(x):
    print i

产生:

3600
1200
3600
300

是正确的数字.

但是,当我这样称呼时:

However, when I call it like so:

somefun(lengths(x))

其中 somefun()定义为:

def somefun(lengths):
    for length in lengths():  # <--- ERROR HERE
        if not is_blahblah(length): return False

我收到此错误消息:

TypeError: 'generator' object is not callable

我误会什么?

推荐答案

您不需要调用生成器,只需删除()括号即可.

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

然后将传递给 somefun 函数的参数绑定到本地 lengen 变量而不是 lengths ,以明确表明该本地变量与您在其他地方定义的 lengths()函数不同.

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.

这篇关于TypeError:“发电机"对象不可调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆