修改其类的数据对象的函数

时间:2016-04-20 23:40:01

标签: python python-2.7

我想定义一个函数,将其命名为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

1 个答案:

答案 0 :(得分: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

参考: