[英]How to call Thread derived class method from run in Python?
Currently I'm not a python programmer, but I'm giving some maintenance to some python code, and I have what's more or less the following: 目前我不是一个python程序员,但我正在对一些python代码进行一些维护,而且我或多或少有以下内容:
class DerivedThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def initStuff():
print "Hello 2"
def run(self):
print "Hello 1"
self.initStuff()
print "Hello 3"
initStuff
does not call print
in truth, just set some variables, I've added this method for organization, there was only __init__
and run
before. initStuff
并没有调用print
,只是设置了一些变量,我已经为组织添加了这个方法,之前只有__init__
并run
。
The problem is that, once execution reachs self.initStuff()
, I see no messages following anymore, only "Hello 1"
, I thought it was some problem with calling derived methods with python, but I don't know what's happening. 问题是,一旦执行到达
self.initStuff()
,我就看不到任何消息了,只有"Hello 1"
,我认为用python调用派生方法有些问题,但我不知道发生了什么。
What's happening? 发生了什么?
The problem is in definition of your initStuff
method. 问题在于
initStuff
方法的定义。 It requires at least one argument (usually called 'self') in it's definition (you've defined no arguments). 它在定义中至少需要一个参数(通常称为“self”)(你没有定义参数)。 Let's see what happens then:
让我们看看会发生什么:
class MyClass(object):
def initStuff(self):
pass
c = MyClass()
c.initStuff()
TypeError: initStuff() takes no arguments (1 given)
So obviously your code fails silently in thread you've defined. 显然,您的代码在您定义的线程中无声地失败。
The way to fix the problem is to define initStuff
method following Python rules. 解决问题的方法是根据Python规则定义
initStuff
方法。
...
def initStuff(self): # Here 'self' argument is defined
pass
This kind of method is called instancemethod as it's called on behalf of your class instance (and the first argument is an instance object itself that must be explicitly defined). 这种方法称为instancemethod,因为它代表您的类实例调用(第一个参数是必须显式定义的实例对象本身)。
Read more about classes in documentation . 阅读有关文档中的类的更多信息
哦,我明白了,我只需要将self
作为参数传递给initStuff
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.