Python 为什么线程中调用函数的部分代码没有被执行
我在联机中找到了这段代码,在运行这段代码时,我发现printThis非常糟糕{}。formatself这部分没有被执行。但是如果我 如果不使用if-like运行,则两个函数都是自连接的。我不知道为什么会发生这种情况。你能描述一下吗Python 为什么线程中调用函数的部分代码没有被执行,python,python-multithreading,Python,Python Multithreading,我在联机中找到了这段代码,在运行这段代码时,我发现printThis非常糟糕{}。formatself这部分没有被执行。但是如果我 如果不使用if-like运行,则两个函数都是自连接的。我不知道为什么会发生这种情况。你能描述一下吗 class MyThread(Thread): def __init__(self, val): ''' Constructor. ''' Thread.__init__(self) self.val = v
class MyThread(Thread):
def __init__(self, val):
''' Constructor. '''
Thread.__init__(self)
self.val = val
def run(self):
for i in range(1, self.val):
print('Value %d in thread %s' % (i, self.getName()))
self.printing_fun()
# Sleep for random time between 1 ~ 3 second
#secondsToSleep = randint(1, 5)
#time.sleep(secondsToSleep)
def connecting(self):
print "Establishing connection right now........."
def printing_fun(self):
# if i run like self.connecting() without previous if then all are
working fine.
if self.connecting():
print("This is awefull {}".format(self))
# Run following code when the program starts
if __name__ == '__main__':
# Declare objects of MyThread class
myThreadOb1 = MyThread(4)
myThreadOb1.setName('Thread 1')
myThreadOb2 = MyThread(4)
myThreadOb2.setName('Thread 2')
# Start running the threads!
myThreadOb1.start()
myThreadOb2.start()
# Wait for the thre`enter code here`ads to finish...
myThreadOb1.join()
myThreadOb2.join()
print('Main Terminating...')
结果:
与线程无关。请看以下代码:
def connecting(self):
print "Establishing connection right now........."
def printing_fun(self):
# if i run like self.connecting() without previous if then all are
# working fine.
if self.connecting():
print("This is awefull {}".format(self))
self.connecting没有return语句,因此python使其返回None
如果没有:条件永远不会满足:它永远不会进入if
连接是某些连接过程的存根,但它的实现不正确。要正确地存根,您应该让它返回真实的内容:
def connecting(self):
print("Establishing connection right now.........")
return True
self.connecting不返回任何内容,因此python不返回任何内容。这是falsy:所以条件总是False你的连接方法不返回布尔值,所以它总是被计算为'False'运算,我知道了..谢谢@Jean Françoisfare
def connecting(self):
print("Establishing connection right now.........")
return True