6

現在、クロージャーを使用して、次の単純化された例のように関数を生成しています。

def constant_function(constant):
    def dummyfunction(t):
        return constant
    return dummyfunction

これらの生成された関数は、カスタム クラスの init-method に渡され、インスタンス属性として格納されます。欠点は、クラスインスタンスがピクルできなくなることです。したがって、クロージャを回避する関数ジェネレータを作成する方法があるかどうか疑問に思っています。

4

2 に答える 2

7

呼び出し可能なクラスを使用できます。

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

def constant_function(constant):
    return ConstantFunction(constant)

次に、関数のクロージャ状態が代わりにインスタンス属性に転送されます。

于 2013-02-22T16:31:21.377 に答える