本文實例分析了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()
輸出的結果:
新聞熱點
疑難解答