【问题标题】:What does setattr function do in this threading codesetattr 函数在这个线程代码中做了什么
【发布时间】:2017-10-04 14:15:56
【问题描述】:

我正在学习一段代码如下:

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是做什么的,有人可以解释一下吗?

非常感谢

【问题讨论】:

  • 相当于self._thread = thread。您阅读过setattr 文档吗?
  • Using setattr() in python的可能重复
  • 是的,我明白了,但我不明白我们为什么要设置这样的属性。
  • 我们不可能知道为什么你的代码设置了这个属性。我们对TestApp TestWrapper TestClient 类一无所知。所以我最好的猜测是:你设置属性是因为你想稍后访问它。

标签: python multithreading


【解决方案1】:
setattr(object, name, value)

该函数将值分配给所提供对象的属性。例如:setattr(objectA, 'attr', 'foo') 等价于x.foobar = 'foo'

在您的代码中: setattr(self, "_thread", thread) 等价于self._thread=thread

欲了解更多信息,您可以访问python_setattr

希望对你有帮助!

【讨论】:

  • 谢谢。我明白了,但我仍然不知道为什么我们设置属性 _thread 等于线程?
猜你喜欢
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
相关资源
最近更新 更多