Basic Python Tutorials (10)

Source: Internet
Author: User

Magical methods, attributes


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:    __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):        'hello. I am A.'class B (A): pass>>> a = A () >>> B = B () >>> A.hello () H Ello. 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):        'hello. I am A.'classdef'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:

ClassBird:Def__init__ (self): self.hungry = True  Def Eat (self): if Self.hungry: print  ' aaaah ...  '  self.hungry = False else: print  no, Thanks!" >>> b = Bird () >>> () aaaah...> >> () 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:

ClassBird:Def__init__(self): Self.hungry =TrueDefEat (self):IfSelf.hungry:Print‘Aaaah ...‘Self.hungry =FalseElse:Print‘No, thanks!‘ClassSongBird (Bird):Def__init__(self): Self.sound =‘squawk!‘DefSing (self):Printself.sound>>> s = SongBird () >>>  s.sing () Squawk!>>> () Traceback (most Recent call last): File  "<pyshell#26>", line 1, in <module> () File Span style= "COLOR: #800000" > "c:/python27/bird", line 6, Span style= "COLOR: #0000ff" >in eat if Self.hungry:AttributeError: " songbird "object has no attribute " hungry< Span style= "COLOR: #800000" > "           

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

ClassBird:Def__init__(self): Self.hungry =TrueDefEat (self):IfSelf.hungry:Print‘Aaaah ...‘Self.hungry =FalseElse:Print‘No, thanks! "class SongBird (Bird): Span style= "COLOR: #0000ff" >def __init__ (self): bird. __init__ (self) Self.sound =  "squawk!" Span style= "COLOR: #0000ff" >def Sing (self): print self.sound>>> s = SongBird () >>> s.sing () Squawk!>>> () Aaaah...>>> () 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#Indicates that the new classClassBird:Def__init__(self): Self.hungry =TrueDefEat (self):IfSelf.hungry:Print‘Aaaah ...‘Self.hungry =FalseElse:Print‘no, thanks!  "class SongBird (Bird): Span style= "COLOR: #0000ff" >def __init__ (self): super (songbird,self). __init__ () Self.sound = Span style= "COLOR: #800000" > ' squawk! ' def Sing (self): print  Self.sound>>> s.sing () squawk!>>>< Span style= "COLOR: #000000" > () Aaaah...>>> () 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.


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__< Span style= "COLOR: #000000" (self): self.width = 0 self.height = 0 def SetSize (self,size): Self.width, Self.height = size def GetSize (self): Span style= "COLOR: #0000ff" >return Self.width, self.height>>> R = Rectangle () >>> r.width = 10>>> R.height = 5>>>  R.getsize () (Ten, 5) >>> R.setsize ((150,100) >>> r.width150      

In the example above, thegetsize and setSize methods have an accessor method named size with an imaginary attribute, and thesize is determined by the width and height constituent tuples.

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__ =TypeClassRectangle: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.size (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 sizein the same way.

Basic Python Tutorials (10)

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: 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.