打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
巧用Python装饰器 免去调用父类构造函数的麻烦

先看一段代码:

复制代码 代码如下:

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)

当然作用都是调用父类的构造函数。

写了这么久的python代码,每次写到这都有重复造轮子的感觉。刚才突然想到装饰器这个好东西,试着写了个autoInitClass来帮助pythoner脱离苦海,免去手动调用父类构造函数的麻烦。
代码如下:
复制代码 代码如下:

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装饰器构造新类:

复制代码 代码如下:

@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 ,转载请注明原文出处
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
自制录屏软件,不到30行代码(仅供学习研究)
Python self用法详解
十六、Python super()函数:调用父类的构造方法
学 Python 这么久,终于把类函数 & 成员函数 & 静态函数给整明白了!
__init__和__del__
python实现线程池
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服