擅长:python、mysql、java
<p>这里是交易:在<code>ReaderThread</code>处有<code>data</code>字段,在<code>MainThread</code>处有<code>data</code>字段。当在<code>ReaderThread</code>中执行此<code>self.data = smth</code>时,可以为<code>ReaderThread</code>字段设置此值,但从不访问<code>MainThread</code>的任何属性。这两个实例具有相似的命名字段,但它们不相同</p>
<p>要实现您想要的,您应该从<code>ReaderThread.run</code>返回一个值,或者将<code>MainThread</code>实例传递给<code>ReaderThread</code>以便能够修改它。看起来选项2更适合你</p>
<pre><code>class ReaderThread(threading.Thread)
def __init__(self, main_instance):
self.main = main_instance
self.exit = False
def run(self):
while not self.exit:
self.main.data = whatever
def stop(self):
self.exit = True
self.join()
class MainThread():
def __init__(self):
self.data = set()
self.thread = ReaderThread(self)
def function(self):
self.thread.start()
whoptydoo
self.thread.stop()
</code></pre>
<p>顺便说一句,仔细看之后,我对你做错了什么有了另一个想法。由于<code>MainThread.data</code>是一个<code>set()</code>,因此是可变的-您的代码将按原样工作,但前提是您准确地<strong>修改</strong>{<cd1>},而不是重新分配它(我怀疑您本可以这样做)</p>