巧用Python装饰器 免去调用父类构造函数的麻烦
2012-05-18 00:00
1021 查看
先看一段代码:
代码定义了一个继承自threading.Thread的class,看这句
super(T1, self).__init__()
也有些人喜欢这么写
threading.Thread.__init__(self)
当然作用都是调用父类的构造函数。
写了这么久的python代码,每次写到这都有重复造轮子的感觉。刚才突然想到装饰器这个好东西,试着写了个autoInitClass来帮助pythoner脱离苦海,免去手动调用父类构造函数的麻烦。
代码如下:
使用autoInitClass装饰器构造新类:
本文来自: itianda's blog ,转载请注明原文出处
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装饰器实例:调用参数合法性验证
- Python装饰器实例:调用参数合法性验证
- 在java中调用python方法
- 零基础学python-15.3 函数的定义、调用与多态
- 使用Python 3.0a1 调用外部应用程序
- python3调用Google翻译
- Python学习笔记(10)-函数-函数定义、调用、参数、返回值、嵌
- Python调用WebService
- Python调用C的DLL和VC调用有什么区别?
- 在Java中调用Python
- python调用C/C++动态链接库和jython
- c# 调用python
- python3 第二十二章 - 函数式编程之Decorator(装饰器)
- 深度学习(PYTORCH)-2.python调用dlib提取人脸68个特征点
- Python如何调用R:rpy2使用介绍
- java内调用perl、python、dll、cmd
- Python:高级主题之(属性取值和赋值过程、属性描述符、装饰器)
- python调用Java-JPype使用介绍(一)(转)
- 【转】Python装饰器与面向切面编程