python闭包+ oop [英] python closure + oop

查看:95
本文介绍了python闭包+ oop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些有点奇怪(至少对我)与python关闭。说我有这样的2个类:

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()

因此,对象a的方法返回一个要被对象b使用的闭包,而闭包函数将绑定到对象b,在:

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

我的问题是:是否还有允许closure()方法访问对象的属性,方法a?

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

/ p>

Thanks,

推荐答案

给内部的另一个名字:

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

另外,而不是使用types.MethodType,你可能想使用functools.partial

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

这篇关于python闭包+ oop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆