巧用Python裝飾器 免去調(diào)用父類構(gòu)造函數(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
代碼定義了一個繼承自threading.Thread的class,看這句
super(T1, self).__init__()
也有些人喜歡這么寫
threading.Thread.__init__(self)
當然作用都是調(diào)用父類的構(gòu)造函數(shù)。
寫了這么久的python代碼,每次寫到這都有重復(fù)造輪子的感覺。剛才突然想到裝飾器這個好東西,試著寫了個autoInitClass來幫助pythoner脫離苦海,免去手動調(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)載請注明原文出處
相關(guān)文章
python公司內(nèi)項目對接釘釘審批流程的實現(xiàn)
最近把組內(nèi)的一個項目對接釘釘審批接口,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08Python中的pandas表格模塊、文件模塊和數(shù)據(jù)庫模塊
這篇文章介紹了Python中的pandas表格模塊、文件模塊和數(shù)據(jù)庫模塊,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05keras分類模型中的輸入數(shù)據(jù)與標簽的維度實例
這篇文章主要介紹了keras分類模型中的輸入數(shù)據(jù)與標簽的維度實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07