欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

巧用Python裝飾器 免去調(diào)用父類構(gòu)造函數(shù)的麻煩

 更新時(shí)間:2012年05月18日 17:48:36   作者:  
巧用Python裝飾器 免去調(diào)用父類構(gòu)造函數(shù)的麻煩,需要的朋友可以參考下

先看一段代碼:

復(fù)制代碼 代碼如下:

class T1(threading.Thread):
def __init__(self, a, b, c):
super(T1, self).__init__()
self.a = a
self.b = b
self.c = c

def run(self):
print self.a, self.b, self.c

代碼定義了一個(gè)繼承自threading.Thread的class,看這句

super(T1, self).__init__()

也有些人喜歡這么寫

threading.Thread.__init__(self)

當(dāng)然作用都是調(diào)用父類的構(gòu)造函數(shù)。

寫了這么久的python代碼,每次寫到這都有重復(fù)造輪子的感覺。剛才突然想到裝飾器這個(gè)好東西,試著寫了個(gè)autoInitClass來幫助pythoner脫離苦海,免去手動(dòng)調(diào)用父類構(gòu)造函數(shù)的麻煩。
代碼如下:
復(fù)制代碼 代碼如下:

def autoInitClass(OldClass):
superClass = OldClass.mro()[1]
class NewClass(OldClass):
def __init__(*args):
self = args[0]
superClass.__init__(self)
apply(OldClass.__init__, args)
return NewClass

使用autoInitClass裝飾器構(gòu)造新類:

復(fù)制代碼 代碼如下:

@autoInitClass
class T2(threading.Thread):
def __init__(self, a, b, c):
#不用再寫super(T2, self).__init__()
self.a = a
self.b = b
self.c = c

def run(self):
print self.a, self.b, self.c

本文來自: itianda's blog ,轉(zhuǎn)載請(qǐng)注明原文出處

相關(guān)文章

最新評(píng)論