Using the Python decorator without calling the parent class constructor

Source: Internet
Author: User
Tags python decorator
Using the Python decorator without the trouble of calling the parent class constructor, you can refer to the following code:

The code is as follows:


Class T1 (threading. Thread ):
Def _ init _ (self, a, B, c ):
Super (T1, self). _ init __()
Self. a =
Self. B = B
Self. c = c

Def run (self ):
Print self. a, self. B, self. c


The code defines a class inherited from threading. Thread.

Super (T1, self). _ init __()

Some people like to write it like this.

Threading. Thread. _ init _ (self)

Of course, the role is to call the constructor of the parent class.

After writing python code for so long, every time I write it, I feel like repeating the wheel. Just now I suddenly thought of the decorator. I tried to write an autoInitClass to help pythoner break away from the bitter sea, saving the trouble of manually calling the parent class constructor.
The code is as follows:

The code is as follows:


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


Use the autoInitClass modifier to construct a new class:

The code is as follows:


@ AutoInitClass
Class T2 (threading. Thread ):
Def _ init _ (self, a, B, c ):
# Super (T2, self). _ init __()
Self. a =
Self. B = B
Self. c = c

Def run (self ):
Print self. a, self. B, self. c


This article is from: itianda's blog. For more information, see source of the original article.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.