我正在尝试使用Python闭包来做一些有点奇怪的事情(至少对我来说是这样)。假设我有2个类,如下所示:
对象a的方法返回一个闭包,供对象b使用,闭包函数将绑定到对象b,因为上述代码将导致:
我的问题是:有没有办法让 closure() 方法访问对象 a 的属性和方法?
谢谢。
#!/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()
对象a的方法返回一个闭包,供对象b使用,闭包函数将绑定到对象b,因为上述代码将导致:
closure 10, 1
我的问题是:有没有办法让 closure() 方法访问对象 a 的属性和方法?
谢谢。