2016-04-20 73 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 __()'更受歡迎。 –

相關問題