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

yipeiwu_com5年前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中使用装饰器时需要注意的一些问题

装饰器基本概念 大家都知道装饰器是一个很著名的设计模式,经常被用于AOP(面向切面编程)的场景,较为经典的有插入日志,性能测试,事务处理,Web权限校验,Cache等。 Python语言...

Python复制目录结构脚本代码分享

引言   有个需要,需要把某个目录下的目录结构进行复制,不要文件,当目录结构很少的时候可以手工去建立,当目录结构复杂,目录层次很深,目录很多的时候,这个时候要是还是手动去建立的话,实在不...

python操作 hbase 数据的方法

配置 thrift python使用的包 thrift 个人使用的python 编译器是pycharm community edition. 在工程中设置中,找到project inte...

python函数修饰符@的使用方法解析

python函数修饰符@的作用是为现有函数增加额外的功能,常用于插入日志、性能测试、事务处理等等。 创建函数修饰符的规则: (1)修饰符是一个函数 (2)修饰符取被修饰函数为参数...

Python 实现将数组/矩阵转换成Image类

Python 实现将数组/矩阵转换成Image类

先说明一下为什么要将数组转换成Image类。我处理的图像是FITS (Flexible Image Transport System)文件,是一种灰度图像文件,也就是单通道图像。 FIT...