1

I am learning a piece of code as follows:

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()

I am interested in its threading component, I do not understand what setattr does here, can someone please explain?

Many thanks

Liam
  • 1,287
  • 2
  • 9
  • 10
  • It's equivalent to `self._thread = thread`. Have you read the `setattr` documentation? – Aran-Fey Oct 04 '17 at 14:17
  • 1
    Possible duplicate of [Using setattr() in python](https://stackoverflow.com/questions/9561174/using-setattr-in-python) – Rach Sharp Oct 04 '17 at 14:21
  • Yes, I get that, but I don't why we set an attribute like that. – Liam Oct 04 '17 at 14:23
  • 2
    We can't possibly know why _your_ code sets that attribute. We don't know anything about the `TestApp` class _or_ the `TestWrapper` class _or_ the `TestClient` class. So my best guess is: You're setting the attribute because you want to access it later. – Aran-Fey Oct 04 '17 at 14:37

1 Answers1

0
setattr(object, name, value)

The function assigns the value to the attribute of the provided object. For example: setattr(objectA, 'attr', 'foo') is equivalent to x.foobar = 'foo'.

In your code: setattr(self, "_thread", thread) is equivalent to self._thread=thread.

For more information you could visit python_setattr

I hope this help you!

Dayana
  • 1,500
  • 1
  • 16
  • 29
  • Thanks. I get that, but I still dont know why we set an attribute _thread equals thread? – Liam Oct 04 '17 at 14:28