巧用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 ,转载请注明原文出处
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
python如何查看网页代码
用python查看网页代码的方法:1、使用“import”导入requests包import requests2、使用requests包的get()函数通过网页...
[阅读全文]
-
-
python如何保存文本文件
python保存文本文件的方法:使用python内置的open()类可以打开文本文件,向文件里面写入数据可以用write()函数,写完之后,使用close()函...
[阅读全文]
-
python如何编写win程序
python可以编写win程序。win程序的格式是exe,下面我们就来看一下使用python编写exe程序的方法。编写好python程序后py2exe模块即可将...
[阅读全文]
-
-
-
-
-
-
网友评论