Python 3.x Study Notes 10 (destructor and inheritance), python3.x
1. Usage of class variables:
Common attributes to save overhead (memory)
2. destructor
Executed when an instance is released or destroyed, usually used for some final work, such as closing some database links and opening temporary files.
3. Private Method
The method is declared as a private method and cannot be called outside the class.
4. Private attributes
The attribute is declared as private and cannot be used outside the class or accessed directly.
5.
To override the constructor during inheritance, you must first write all the parameters of the parent class and add the subclass variables, then call the parent class, and then add the instantiated variables of the subclass.
6.
Python2.x classic classes are inherited first by depth, while new classes are inherited first by breadth.
Python3.x classic classes and new classes are inherited by breadth first.
Exercise
1 # parent class 1 2 class Person (object): # New Style 3 4 def _ init _ (self, name, age): 5 # constructor 6 self. name = name # instantiate a variable (static attribute) with the scope of 7 self. age = age 8 self. friends = [] 9 10 def eat (self): # class method function (dynamic attribute) 11 print ('% s will eat something! '% Self. name) 12 13 def run (self): 14 print (' % s will runing! '% Self. name) 15 16 def sleep (self): 17 print (' % s will sleep! '% Self. name) 18 19 # parent class 220 class Relation (object): 21 def make_friends (self, obj): 22 print ('% s make friend with % s' % (self. name, obj. name) 23 self. friends. append (obj) # The input parameter here is obj. In this example, obj is both w124 25 26 # subclass 27 class Man (Person, Relation ): # inherit 28 def _ init _ (self, name, age, money): # rewrite constructor 29 # Person. _ init _ (self, name, age, money) # The typical expression is 30 super (Man, self ). _ init _ (name, age) # new writing method. We recommend that you use 31 self. money = money32 33 def piao (self): 34 print ('% s is piaoing ....... '% self. name) 35 36 37 # subclass 38 class Woman (Person, Relation): # inherit 39 def piao (self ): 40 print ('% s is piaoing ....... '% self. name) 41 42 m1 = Man ('zhang san', 20, 10) 43 44 w1 = Woman ('lili', 21) 45 46 m1.make _ friends (w1) 47 print (m1.friends [0]. name) 48 print (m1.friends [0]. age) 49 50 # m1.piao () 51 # m1.eat () 52 # m1.run () 53 # m1.sleep ()