python多线程用法实例详解

2019-10-05 10:37:07丽君

本文实例分析了python多线程用法。。具体如下:

今天在学习尝试学习python多线程的时候,突然发现自己一直对super的用法不是很清楚,所以先总结一些遇到的问题。当我尝试编写下面的代码的时候:

class A():
    def __init__( self ):
        print "A"
class B( A ):
    def __init__( self ):
        super( B, self ).__init__(  )
# A.__init__( self )
        print "B"
b = B()
出现:

super( B, self ).__init__()

TypeError: must be type, not classobj

最后发现原来是python中的新式类的问题,也就是A必须是新式类。解决方法如下两种:

(1)
class A( object ):
    def __init__( self ):
        print "A"
class B( A ):
    def __init__( self ):
        super( B, self ).__init__(  )
# A.__init__( self )       ##这条语句是旧式的,存在潜在的问题,应该避免使用
        print "B"
b = B()

(2)
__metaclass__=type
class A():
    def __init__( self ):
        print "A"
class B( A ):
    def __init__( self ):
        super( B, self ).__init__(  )
# A.__init__( self )    ##这条语句是旧式的,存在潜在的问题,应该避免使用
        print "B"
b = B()
注意:如果在super( B, self ).__init__(  )

语句中添加self,也就是super( B, self ).__init__( self ),会出现如下的错误:

    super( B, self ).__init__( self )

TypeError: __init__() takes exactly 1 argument (2 given)

以上只是一点点本人的心得笔记,呵呵。
import threading, time
class myThread( threading.Thread ):
    def __init__( self, threadname = "" ):
        #threading.Thread.__init__( self, name = threadname )
        super( myThread, self ).__init__( name = threadname )
    def run( self ):
        print "starting====", self.name, time.ctime()
        time.sleep( 5 )
        print "end====", self.name, time.ctime(),
 
m = myThread( "m" )
n = myThread( "n" )
 
m.start()
n.start()
输出的结果: