Python BASICS (10) and python BASICS (
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.
class NewType(Object): mor_code_hereclass OldType: 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.
class FooBar: 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.
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 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:
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 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 code to initialize the hungry feature. 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 an instance method is called, the self parameter of the method 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 the required self parameter (this method is called the unbound method ).
By providing the current instance as the self parameter to the unbound method, SongBird can use all its superclass constructor methods, that is, the property hungry can be set.
Ii. Use the super Function
_ Metaclass _ = type # indicates the new 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!
Super functions can only be used in new classes. The current class and object can be used as parameters of the super function. Any method that calls the object returned by the function calls the superclass method instead of the method of the current class. So we can use Bird in different SongBird constructor methods, and directly use super (SongBird, self ).
Attribute
The accessor is a simple method. It can use names like getHeight and setHeight to 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.width150
In the preceding example, the getSize and setSize methods are an accessors method named size, which is a tuple consisting of width and height.
Property Function
The use of the property function is very simple. If you have compiled a class like the Rectangle in the previous section, you only need to 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.size(10, 5)>>> r.size = 150,100>>> r.width150
In this new version of Retangle, the property function creates an attribute, in which the accessors function is used as a parameter (value first, then value assignment), and this attribute is named size. In this way, you no longer need to worry about how to implement it. You can use the same method to process width, height, and size.