Python 修改其类的函数';s数据对象

Python 修改其类的函数';s数据对象,python,python-2.7,Python,Python 2.7,我想定义一个函数,调用它test\u controller(),然后我想把这个函数传递给构造函数:my\u thing=TestClass(test\u controller)。此函数需要能够修改其类的数据对象。我听说过Python3的非本地关键字,但我正在运行Python2.7。可能吗?我该怎么做?这是我已经尝试过的 class TestClass(object): def __init__(self, ctrl_func): self.a = 4 s

我想定义一个函数,调用它
test\u controller()
,然后我想把这个函数传递给构造函数:
my\u thing=TestClass(test\u controller)
。此函数需要能够修改其类的数据对象。我听说过Python3的
非本地
关键字,但我正在运行Python2.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

可以传入对要修改的任何对象的引用

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\u 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
参考:


@Taylor-注意第二个例子中的变化<代码>类型。MethodType()似乎比
更受欢迎。