python closure + oop

谁都会走 提交于 2019-12-10 19:11:33

问题


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



来源:https://stackoverflow.com/questions/7692423/python-closure-oop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!