简单地将变量传递给类
为什么这不起作用?
class spin(threading.Thread):
def __init__(self):
super(spin,self).__init__()
self._stop = False
def run (self,var):
self.var=var
print self.var
def echo (self,var):
self.var=var
print self.var
if __name__ == '__main__':
s = spin()
s.start('hello')
但这呢?
s = spin()
s.echo('hello')
我猜测是因为启动序列需要在 init 中定义?但不知道如何。有人询问错误代码:
s.start('hello')
TypeError: start() takes exactly 1 argument (2 given)
Why doesn't this work ?
class spin(threading.Thread):
def __init__(self):
super(spin,self).__init__()
self._stop = False
def run (self,var):
self.var=var
print self.var
def echo (self,var):
self.var=var
print self.var
if __name__ == '__main__':
s = spin()
s.start('hello')
but this does?
s = spin()
s.echo('hello')
Im guessing its because the start sequence needs to be defined in the init ? but not sure how. someone asked for error codes from this:
s.start('hello')
TypeError: start() takes exactly 1 argument (2 given)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
s.start('hello')
不起作用的原因是继承的Threadin.start()
方法除了self
之外不接受任何参数。调用 s.echo('hello') 似乎确实有效,但它在主线程的上下文中调用该函数,而不是生成一个新线程。
修复代码的一种方法是将
var
提供给构造函数:The reason
s.start('hello')
does not work is that the inheritedThreadin.start()
method takes no arguments other thanself
.Calling
s.echo('hello')
does appear to work, but it calls the function in the context of the main thread instead of spawning a new thread.One way to fix your code is by supplying
var
to the constructor: