2016-04-20 101 views
1

我想定义一个函数,将其称为test_controller(),并且我想将此函数传递给构造函数:my_thing = TestClass(test_controller)。该功能需要能够修改其类的数据对象。我听说过Python 3的nonlocal关键字,但我正在运行Python 2.7。可能吗?我该怎么做呢?这是我已经尝试过的。修改其类的数据对象的函数

class TestClass(object): 

    def __init__(self, ctrl_func): 
     self.a = 4 
     self.ctrl_func = ctrl_func 

    def do_stuff(self): 
     self.ctrl_func() 

def test_controller(): 
    global a 
    a = 20 

my_thing = TestClass(test_controller) 
print my_thing.a   #this prints 4 
my_thing.ctrl_func() 
print my_thing.a   #this prints 4 but I want it to print 20 

回答

3

您可以传递任何您想要修改的对象的引用。

class TestClass(object): 

    def __init__(self, ctrl_func): 
     self.a = 4 
     self.ctrl_func = ctrl_func 

    def do_stuff(self): 
     self.ctrl_func(self) 

def test_controller(self): 
    self.a = 20 

my_thing = TestClass(test_controller) 
print my_thing.a   #this prints 4 
my_thing.ctrl_func(my_thing) 
print my_thing.a   #this prints 4 but I want it to print 20 

或者,您可以ctrl_func转换为对象的绑定方法:

import types 

class TestClass(object): 

    def __init__(self, ctrl_func): 
     self.a = 4 
     self.ctrl_func = types.MethodType(ctrl_func, self) 

    def do_stuff(self): 
     self.ctrl_func() 

def test_controller(self): 
    self.a = 20 

my_thing = TestClass(test_controller) 
print my_thing.a   #this prints 4 
my_thing.ctrl_func() 
print my_thing.a   #this prints 4 but I want it to print 20 

参考:

+0

看起来不错, 谢谢。看来self.ctrl_func()也可以工作 – Taylor

+1

@Taylor - 第二个示例中的注释更改。 'types.MethodType()'似乎比'__get __()'更受欢迎。 –

相关问题