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

4
  • It's equivalent to self._thread = thread. Have you read the setattr documentation? Commented Oct 4, 2017 at 14:17
  • 1
    Possible duplicate of Using setattr() in python Commented Oct 4, 2017 at 14:21
  • Yes, I get that, but I don't why we set an attribute like that. Commented Oct 4, 2017 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. Commented Oct 4, 2017 at 14:37

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I get that, but I still dont know why we set an attribute _thread equals thread?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.