A detailed description of the Python magic method

Source: Internet
Author: User
Preparatory work

To ensure that the class is a new class, you should put the _metaclass_=type into the beginning of your module.

Class NewType (Object): Mor_code_hereclass oldtype:mor_code_here


In this two class Newtype is the new class, Oldtype belongs to the old class, if preceded by _metaclass_=type, then two classes belong to the new class.

Construction method

The construction method is different from its method, and the constructor method is called immediately when an object is created. Creating a Python constructor is a simple answer, as long as the Init method, from the simple Init method, is converted to the magic version of the _init_ method.

Class FooBar:    def __init__ (self):        Self.somevar =          >>> F =foobar () >>> f.somevar42


Override a general method

Each class may have one or more superclass (parent class) that inherit the behavior method from the superclass.

Class A:    def hello (self):        print ' Hello. I am A. ' Class B (A): pass>>> a = a () >>> B = B () >>> A.hello () hello. I am A.


Because Class B does not have a Hello method, Class B inherits the Class A, so the Class A Hello method is called.

The most basic way to add functionality to a subclass is to add a method. However, you can also override some superclass methods to customize the behavior of the inheritance. As follows:

Class A:    def hello (self):        print ' Hello. I am A. ' Class B (a):    def hello (self):        print ' Hello. I am  b ' >>> B = B () >>> B.hello () hello. I am  B


Special and constructive methods

Rewriting is an important element in the inheritance mechanism, which is especially important for a construction method. Look at the following example:

Class Bird:    def __init__ (self):        self.hungry = True    def eat (self):        if self.hungry:            print ' Aaaah ... '            self.hungry = False        else:            print ' No, thanks! ' >>> B = Bird () >>> b.eat () aaaah...>>> b.eat () No, thanks!


This class defines the bird's ability to eat, and once it has eaten once again it will not be hungry, and can be clearly seen through the above results.

Then use the Songbird class to inherit the bird class and add a way to sing it:

Class Bird:    def __init__ (self):        self.hungry = True    def eat (self):        if self.hungry:            print ' Aaaah ... '            self.hungry = False        else:            print ' No, thanks! '              Class SongBird (Bird):         def __init__ (self):                 self.sound = ' squawk! '         def sing (self):                 print self.sound>>> s = SongBird () >>> s.sing () squawk!>>> s.eat () Traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
       s.eat ()  file "c:/ Python27/bird ", line 6, in Eat    if Self.hungry:AttributeError: ' SongBird ' object have no attribute ' hungry '
  
 
   
  


The exception clearly illustrates the error: Songbird has no hungry feature. The reason is this: in Songbird, the constructor method is overridden, but the new constructor does not have any code for initializing the hungry attribute. To achieve the desired effect, the Songbird constructor must call its superclass bird construction method to ensure basic initialization.

Two methods are implemented:

First, call the unbound superclass construction method

Class Bird:    def __init__ (self):        self.hungry = True    def eat (self):        if self.hungry:            print ' Aaaah ... '            self.hungry = False        else:            print ' No, thanks! '              Class SongBird (Bird):         def __init__ (self):                 bird.__init__ (self)                 self.sound = ' squawk! '         def sing (self):                 print self.sound>>> s = SongBird () >>> s.sing () squawk!>>> s.eat () aaaah ...>>> s.eat () No, thanks!


A line of code bird.__init__ (self) has been added to the Songbird class. When you invoke the method of an instance, the self parameter of the method is automatically bound to the instance (this is called the binding method). But if the method of the class is called directly, then no instance is bound. This gives you the freedom to provide the self parameter you need (such a method is called an unbound method).

By providing the current instance as the self parameter to the unbound method, Songbird is able to use all the implementations of its superclass construction method, which means that the property hungry can be set.

Second, use Super function

__metaclass__ = Type  #表明为新式类class Bird:    def __init__ (self):        self.hungry = True    def eat (self):        if Self.hungry:            print ' Aaaah ... '            self.hungry = False        else:            print ' No, thanks! '              Class SongBird (Bird):         def __init__ (self):                 super (Songbird,self). __init__ () self.sound                 = ' squawk! '         def sing (self):                 print self.sound>>> s.sing () squawk!>>> s.eat () aaaah...>>> s.eat () No , thanks!


The super function can only be used in modern classes. The current class and object can be used as arguments to the Super function, and any method that invokes the object returned by the function is called a method of the superclass, not the method of the current class. It is possible to use the bird in the SongBird construction method and use Super (songbird,self) directly.

Property

Accessors are an easy way to get or rebind some features using the names of GetHeight, SetHeight. If you have to take some action when accessing a given attribute, encapsulating state variables like this are important. As follows:

Class Rectangle:    def __init__ (self):        self.width = 0        self.height = 0    def setSize (self,size):        Self.width, self.height = size    def getsize (self):        return self.width, self.height>>> r = Rectangle () ;>> r.width = 10>>> r.height = 5>>> r.getsize () (5) >>> r.setsize ((150,100)) >> > r.width150


In the example above, the GetSize and SetSize methods are accessor methods of an imaginary attribute named size, which is a tuple of width and height.

Property function

The use of the property function is simple, if you have written a class like the previous section of rectangle, then just add a line of code:

__metaclass__ = Typeclass Rectangle:    def __int__ (self):        self.width = 0        self.height = 0    def setSize (self , size):        self.width, self.height = size    def getsize (self):        return self.width, self.height    size = Property (GetSize, setSize) >>> r = Rectangle () >>> r.width = 10>>> r.height = 5>>> r.si Ze (5) >>> r.size = 150,100>>> r.width150


In this new version of Retangle, the property function creates an attribute where the accessor function is used as a parameter (first value, then Assignment), which is the life of size. This eliminates the need to worry about how it is implemented, and can handle width, height, and size in the same way.

  • Related 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.