巧用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)文章
python公司內(nèi)項(xiàng)目對(duì)接釘釘審批流程的實(shí)現(xiàn)
最近把組內(nèi)的一個(gè)項(xiàng)目對(duì)接釘釘審批接口,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08Python的lambda匿名函數(shù)的簡(jiǎn)單介紹
Python的lambda匿名函數(shù)的簡(jiǎn)單介紹,需要的朋友可以參考一下2013-04-04Python中的pandas表格模塊、文件模塊和數(shù)據(jù)庫模塊
這篇文章介紹了Python中的pandas表格模塊、文件模塊和數(shù)據(jù)庫模塊,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05keras分類模型中的輸入數(shù)據(jù)與標(biāo)簽的維度實(shí)例
這篇文章主要介紹了keras分類模型中的輸入數(shù)據(jù)與標(biāo)簽的維度實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07