2017-10-04 33 views
1

我學習一段代碼如下:什麼SETATTR功能做這個線程代碼

class TestApp(TestWrapper, TestClient): 
    def __init__(self, ipaddress, portid, clientid): 
    TestWrapper.__init__(self) 
    TestClient.__init__(self, wrapper=self) 

    self.connect(ipaddress, portid, clientid) 

    thread = Thread(target = self.run) 
    thread.start() 

    setattr(self, "_thread", thread) 

    self.init_error() 

我很感興趣,它的線程組件,我不明白是什麼SETATTR在這裏所做的,可有人請解釋?

非常感謝

+0

它相當於'self._thread = thread'。你讀過'setattr'文檔嗎? –

+1

[在python中使用setattr()]的可能的重複(https://stackoverflow.com/questions/9561174/using-setattr-in-python) –

+0

是的,我明白了,但我不明白爲什麼我們設置了一個屬性像那樣。 – Liam

回答

0
setattr(object, name, value) 

功能分配值所提供的對象的屬性。例如:setattr(objectA, 'attr', 'foo')相當於x.foobar = 'foo'。您的代碼: setattr(self, "_thread", thread)相當於self._thread=thread

欲瞭解更多信息,您可以參觀python_setattr

我希望這可以幫助您!

+0

謝謝。我明白了,但我仍然不知道爲什麼我們設置了屬性_thread等於線程? – Liam