在python中生成没有闭包的函数

jan*_*jan 6 python closures function pickle

现在我正在使用闭包来生成像这个简化示例中的函数:

def constant_function(constant):
    def dummyfunction(t):
        return constant
    return dummyfunction
Run Code Online (Sandbox Code Playgroud)

然后将这些生成的函数传递给自定义类的init方法,该类将它们存储为实例属性.缺点是这使得类实例难以理解.所以我想知道是否有办法创建函数生成器来避免闭包.

Mar*_*ers 8

你可以使用一个可调用的类:

class ConstantFunction(object):
    def __init__(self, constant):
        self.constant = constant
    def __call__(self, t):
        return self.constant

def constant_function(constant):
    return ConstantFunction(constant)
Run Code Online (Sandbox Code Playgroud)

然后,函数的闭包状态将转移到实例属性.