开发者

python closure + oop

开发者 https://www.devze.com 2023-04-11 07:17 出处:网络
I\'m trying to do something a bit strange (at least to me) with python closure. Say I have 2 classes like this:

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 = t开发者_运维问答ypes.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,


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号