Pthon 3.x Learning Note 10 (Destructor and Inheritance)

1. Use of class variables:
Common properties to save money (memory)

2. Destructors
Executed when an instance is released and destroyed, usually to do some finishing work, such as closing some database links and opening temporary files

3. Private methods
Beginning with two underscores, declare that the method is private and cannot be called outside the class.

4. Private Properties
The two underscores begin by declaring that the property is private and cannot be used outside the class ground or accessed directly.

5.

When inheriting, overriding the constructor first writes all the parameters of the parent class once with the subclass variable, then calls the parent class, and then adds the instantiation variable of the subclass.

6.
The python2.x classic class inherits first by depth and the new class inherits first by breadth.

Both python3.x classic and new classes are inherited uniformly by breadth first.

 

Practice

 1 #Parent 1
 2 class Person(object):         #New Style Writing
 3 
 4     def __init__(self,name,age):
 5         #Constructor
 6         self.name = name           #Instantiate variables (static properties), scoped to the instantiation itself
 7         self.age = age
 8         self.friends = []
 9 
10     def eat(self):                  # Class method functionality (dynamic properties)
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 2
20 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 parameter passed here is obj,In this case obj since w1
24 
25 
26 #Subclass
27 class Man(Person,Relation):                      #Multiple Inheritance
28     def __init__(self,name,age,money):           #Override Constructor
29         #Person.__init__(self,name,age,money)     #Classic Writing
30         super(Man,self).__init__(name,age)        #New style of writing, recommended
31         self.money = money
32 
33     def piao(self):
34         print('%s is piaoing .......'% self.name)
35 
36 
37 #Subclass
38 class Woman(Person,Relation):                 #Multiple Inheritance
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()

Keywords: Python Database

Added by jevman on Sun, 19 Apr 2020 19:20:39 +0300