您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/6/16 7:25:24发布31次查看
先看一段代码:
复制代码 代码如下:
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 ,转载请注明原文出处
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product