Magic methods and attributes
------------------------
Preparations
To ensure that the class is a new type of class, you should add _ metaclass _ = type to the beginning of your module.
ClassNewtype (object): mor_code_hereClassOldtype: mor_code_here
In these two classes, newtype is a new class, And oldtype belongs to the old class. If _ metaclass _ = type is added, both classes belong to the new class.
Constructor
The constructor is different from the constructor. when an object is created, the constructor is called immediately. Creating a python constructor is simple. You only need to convert the init method from the simple init method to the _ init _ method of the magic version.
ClassFoobar:Def _ Init __(Self): Self. somevar= 42 >>> F =Foobar ()>>>F. somevar42
Override a general method
Each class may have one or more superclasses (parent classes) that inherit behavior methods from the superclasses.
ClassA:DefHello (Self ):Print 'Hello. I am.'ClassB ():Pass>>> A =A ()>>> B =B ()>>>A. Hello () Hello. I am.
Because Class B does not have the hello method, Class B inherits Class A, so the hello method of Class A is called.
The most basic way to add a function to a subclass is to add a function. However, you can also override some superclasses to customize the inherited behavior. As follows:
ClassA:DefHello (Self ):Print 'Hello. I am.'ClassB ():DefHello (Self ):Print 'Hello. I am B'>>> B =B ()>>>B. Hello () Hello. I am B
Special and constructor
Rewriting is an important part of the inheritance mechanism and is especially important for Constructor methods. See 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. Once it has been eaten, it will become hungry again. The above execution results can be clearly seen.
The songbird class is used to inherit the bird class and add the singing method to 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 call last): File " <Pyshell #26> " , Line 1, In <Module> S. Eat () File " C:/python27/bird " , Line 6, In Eat If Self. Hungry: attributeerror: ' Songbird ' Object has no attribute ' Hungry '
The exception clearly indicates the error: songbird does not have the hungry feature. The reason is: in Songbird, the constructor is overwritten, but the new constructor does not have any information about initializing the hungry feature.Code. To achieve the expected results, the songbird constructor must call its super bird constructor to ensure basic initialization.
Two methods:
1. Call unbound superclass Constructor
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) is added to the songbird class ). When calling an instance methodSelfThe parameter is automatically bound to the instance (this is called the binding method ). However, if you call the class method directly, no instance will be bound. In this way, you can freely provide what you needSelfParameter (such a method is called an unbound method ).
By using the current instanceSelfParameters are provided to the unbound method,SongbirdYou can use all the implementations of its superclass constructor, that is, the attributeHungryCan be set.
Ii. UseSuperFunction
_ Metaclass __ = Type# Indicates a new class 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!
SuperFunctions can only be used in new classes. The current class and object can be usedSuperWhen using function parameters, any method that calls the object returned by the function calls the superclass method, rather than the method of the current class. In this caseSongbirdIs Used in the constructorBird,Direct useSuper (songbird, self).
Attribute
The accessor is a simple method that can be usedGetheight,SetheightTo obtain or rebind some features. If you must take some action to access a given feature, it is important to encapsulate state variables like this. 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 ()( 10, 5 ) >>> R. setsize (150,100 )) >>> R. Width 150
In the preceding example,GetsizeAndSetsizeMethod NameSizeThe method of the accesser of the hypothetical feature,SizeYesbyWidthAndHeight.
PropertyFunction
PropertyFunction usage is very simple. If you have compiledRectangleFor such classes, you only need to add a line of code:
_ Metaclass __ = Type Class 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. Size ( 10, 5 ) >>> R. size = 150,100 >>> R. Width 150
In this new versionRetangleMedium,PropertyThe function creates an attribute, in which the accessor function is used as a parameter (value first, then value assignment ).Size. In this way, you no longer need to worry about how it is implemented. You can use the same method to handle it.Width,HeightAndSize.