简体   繁体   English

python TypeError:'int'对象不可调用

[英]python TypeError: 'int' object is not callable

i have homework and we need to do something like iterator, the func work great but the techer told he run the func with (t=Make_iterator()) like this, what i do wrong? 我有家庭作业,我们需要做类似迭代器的事情,功能很好,但技术人员告诉他使用(t = Make_iterator())这样运行功能,我做错了什么? tnx! tnx!

global x
x=-1

def Make_iterator(fn):
    global x
    x+=1
    return fn(x)

fn=lambda y:y*2

t=Make_iterator(fn)

print(t())

I think you want a closure, which is a function defined within the local namespace of anther function, so that it can access the outer function's variables: 我认为您想要一个闭包,这是在另一个函数的本地名称空间内定义的函数,以便它可以访问外部函数的变量:

def make_iterator(func):
    x = -1
    def helper():
        nonlocal x
        x += 1
        return func(x)
    return helper

The nonlocal statement allows the inner function to modify the variable declared in the outer function (otherwise you'd either get an error, or you'd bind your own local variable without changing the outer one). nonlocal语句允许内部函数修改在外部函数中声明的变量(否则您将得到一个错误,或者在不更改外部变量的情况下绑定自己的局部变量)。 It was only added in Python 3, so if you're still using Python 2, you'll need to wrap the x value in a mutable data structure, like a list. 它仅在Python 3中添加,因此,如果您仍在使用Python 2,则需要将x值包装在可变数据结构(如列表)中。

Another approach to the same idea is to write class, rather than a function. 具有相同想法的另一种方法是编写类而不是函数。 An instance of a class can be callable (just like a function) if the class defines a __call__ method: 如果类的实例定义了__call__方法,则该类的实例可以被调用(就像一个函数一样):

class MyIterator(object):
    def __init__(self, func):
        self.index = -1
        self.func = func

    def __call__(self):
        self.index += 1
        return self.func(self.index)

This can be useful if the state you need to keep track of is more complicated (or should change in more complicated ways) than the simple integer index used in this example. 如果您需要跟踪的状态比本示例中使用的简单整数索引更复杂(或应该以更复杂的方式更改),则此方法很有用。 It also works in Python 2 without annoying workarounds. 它也可以在Python 2中运行,而无需烦人的解决方法。

I think he wants your Make_iterator function to return a function that acts as an iterator. 我认为他想你Make_iterator函数返回充当迭代器的功能 So you could wrap the contents of your current Make_iterator function within an inner function f and return that: 因此,您可以将当前Make_iterator函数的内容包装在内部函数f并返回该内容:

def Make_iterator(fn):
    def f():
        global x
        x+=1
        return fn(x)
    return f

Now if you do t = Make_iterator(fn) , every time you call t() it will return the next value of the iterator, in your case 0, 2, 4, 6, 8, etc... 现在,如果您执行t = Make_iterator(fn) ,则每次调用t() ,它将返回迭代器的下一个值,在您的情况下t = Make_iterator(fn) 0, 2, 4, 6, 8, etc...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM