python closure + oop

2019-07-07 01:41发布

问题:

I'm trying to do something a bit strange (at least to me) with python closure. Say I have 2 classes like this:

#!/usr/bin/python
import types

def method_a(self):
    print "ma %d" % self.val

class A(object):
    def __init__(self):
        self.val = 5
        pass

    def foo(self, a):
        def closure(self):
            print "closure %d, %d" % (self.val, a)
        return closure

class B(object):
    def __init__(self):
        self.val = 10
        pass

    def foo(self):
        print "B::foo %d"  % self.val


a = A()
b = B()
b.undo = types.MethodType(a.foo(1), b)

b.undo()

So object a's method returns a closure to be used by object b and the closure function will be bound to object b as the above code will result in:

closure 10, 1

My question is: is there anyway to allow the closure() method to access attribute, method of object a?

Thanks,

回答1:

Give the inner self another name:

def foo(self, a):
    def closuer(b):
        print "closure %d, %d" % (self.val, a)
    return closuer

Also, rather then using types.MethodType, you might want to use functools.partial