210225 class inheritance
inherit
1. Definition of inheritance
The process of letting subclasses directly own the properties and methods of the parent class
**Subclass** Successor
**Parent class: * * inheritee, also known as superclass
2. Inheritance method
Class subclass (parent class)
pass
**Note: * * if no parentheses are added, the base class object is inherited by default
A subclass can have multiple parent classes and subclasses at the same time (parent class 1, parent class 2,...)
Python subclasses can inherit all the properties of their parent classes and methods
class Person: num = 61 def __init__(self): self.name = 'Xiao Hong' self.age = 18 self.sex = 'female' def eat(self, food): print(f'{self.name}Eating{food}') # Class method @classmethod def show_num(cls): print('Number of humans:', cls.num) # Static method @staticmethod def info(): print('Human destruction of the environment!') class Student(Person): pass stu1 = Student() print(stu1.age, stu1.name, stu1.sex) # 18 little red girl print(Student.num) # 61 stu1.eat('steamed stuffed bun') # Xiao Hong is eating steamed stuffed buns Student.show_num() # Number of humans: 61 Student.info() # Human beings destroy the environment!
Subclass override
1. Add attributes and methods to subclasses
1) Add class properties
You can directly define a new class attribute in the subclass
2) Override: you can add the same method as the parent class in the child class
Call: call directly when rewriting the part with each
When using both overridden and superclass methods, use super() Method (except static method)
Summary: usage of super
super(). Method () directly calls the specified method of the current parent class
Super (class, object) Method ()
Call the specified method of the parent class of the specified class (the object must be the object of the previous class)
3) Add object properties
In subclass_ init _ _ Method to call the _ofthe parent class through super()_ init _ _
class A: x = 100 @staticmethod def func1(): print('A') @classmethod def funca(cls): print('A1') def func4(self): print('A Object method 1') def func5(self): print('A Object method 2') class B(A): y = 20 @classmethod def func2(cls): print('B') @staticmethod def func1(): print('BB') @classmethod def funca(cls): super().funca() """cls.__base__.funca()""" print('B2') def func4(self): super().func4() super().func5() print('B Object method of') @staticmethod def func3(): # super().func1() # report errors super(B, B()).func1() print('B Static state of') class C(B): pass print(A.x) # 100 print(B.x) # 100 print(C.x) # 100 print(B.y) # 20 # print(A.y) print(C.y) # 20 B.func1() # BB A.func1() # A B.funca() # A1 B2 b = B() b.func4() # Object method of A 1 object method of A 2 object method of B B.func3() # Static of a and B class X: def fx(self): print('x') class Y(X): def fy(self): super().fx() """super(Y, self).fx()""" print('y') def f(self): super().fx() super(N, N()).fm() class M: def fm(self): print('m') class N(M): def fn(self): print('n') x = X() y = Y() y.fy() # x y y.f() # x m print('================================================') class Animal: def __init__(self): self.age = 0 self.gender = 'female' class Cat(Animal): def __init__(self): super().__init__() self.color = 'white' self.price = 2000 self.breed = 'wildcat' pass cat = Cat() print(cat.age, cat.gender) # 0 female print(cat.color) # white
Adding object properties
class A: def __init__(self, a, b=10): # a = 200, b=10 self.a = a # 200 self.b = b # 10 self.c = 0 # 0 class B(A): def __init__(self, d, a): # d = 100, a = 200 # super().__init__(100) super(B, self).__init__(a) # A: __init__(200) self.d = d # 100 bb = B(100, 200) # B: __init__(100, 200) print(bb.a, bb.b, bb.c, bb.d) # 200 10 0 100 '''practice: Create a human with attributes: name, age, gender, The name and age must be assigned when the creator's object is required, Gender can be assigned or not assigned (male by default) The created student class has attributes: name, age, gender, student number, credit and telephone, When it is required to create a student object, the name and phone number must be assigned. Age and gender can be assigned or not assigned (18 and years by default), Credit and student number cannot be assigned when they are created. The default values are'000'And 0 ''' class Person: def __init__(self, name, age, gender='male'): self.name = name self.age = age self.gender = gender class Students(Person): def __init__(self, name, tel, age=18, gender='male'): super(Students, self).__init__(name, age, gender) self.study_id = '007' self.score = 0 self.tel = tel p = Person('Xiao Ming', 18) stu = Students('Xiao Hong', '1110', 20, 'female') print(stu) # <__main__.Students object at 0x000000000255B160>
Multiple inheritance
In case of multiple inheritance, subclasses can inherit the class properties and methods of all parent classes,
However, only the object properties of the first parent class can be inherited
_ _ mro _ _ The model is applicable to multi inheritance (understand)
class Animal: num = 61 def __init__(self): self.age = 0 self.gender = 'male' @classmethod def show(cls): print('number:', cls.num) class Fly: name = 'Aerocraft' def __init__(self): self.height = 100 self.time = 3 @staticmethod def message(): print('Aerocraft') class Bird(Fly, Animal): pass print(Bird.num, Bird.name) Bird.show() Bird.message() b = Bird() # print(b.age, b.gender) print(b.height, b.time)
Privatization
Access rights:
1) Public: it can be used and inherited both inside and outside the class
(all properties in Python are public)
2) Protected: it can be used and inherited inside the class
3) Private: used inside a class and cannot be inherited
Add 2 underscores before the attribute name or method name in the Python class__
Property or method can be privatized
Python privatization is a pseudo concept. Adding two underscores is equivalent to changing a storage location
Equivalent to adding 'at the beginning of 2 underscores_ Class name ',
If you want to be inherited, add before_ Class name is enough The essence is public
class A: num = 100 __x = 200 # __ x is private def __init__(self): self.name = 'Xiao Ming' self.__age = 18 # __ age is private def info(self): print('Information:', self.__age) self.__f1() @classmethod def show(cls): print(cls.num, cls.__x) def __f1(self): print('Object method') print(A.num) A.show() # print(A.__x) a = A() print(a.name) # print(a.__age) a.info() # a.__f1() print(a.__dict__) # {'name': 'Xiao Ming', '_a_age': 18} print(a._A__age) # 18
Copy
Light copy and deep copy
**The same point: * * will copy the copied object, generate a new object, and then assign a value with the new object
**Differences: * * if the copied object has subclasses, the shallow copy copies only the parent class, and the deep copy copies both
# Import copy module from copy import copy, deepcopy class Dog: def __init__(self): self.name = 'Wangcai' self.gender = 'male dog' def __repr__(self): return f'<{str(self.__dict__)[1:-1]},id:{id(self)}>' class Person: def __init__(self, name, age=18, gender='female'): self.name = name self.age = age self.gender = gender self.dog = Dog() def __repr__(self): return f'<{str(self.__dict__)[1:-1]}, id:{id(self)}>' p1 = Person('Xiao Ming', 20, 'male') p2 = p1 # Direct assignment, assign the address in p1 to p2 p3 = copy(p1) # Light copy. Copy p1 to generate a new object, and assign a value to p3 with the new object p4 = deepcopy(p1) # Deep copy. Copy p1 to generate a new object and assign p4 a value with the new object print('Original data:', p1) print('Direct assignment:', p2) print('Shallow copy:', p3) print('Deep copy:', p4) print('=================================') p1.name = 'floret' p1.dog.gender = 'Bitch' print('Original data:', p1) print('Direct assignment:', p2) print('Shallow copy:', p3) print('Deep copy:', p4) # practice: A = [10, 20, 30, ['abc', '123']] B = A C = copy(A) D = deepcopy(A) A.append(100) # A=[10, 20, 30, ['abc', '123'], 100] A[3].pop() # A=[10, 20, 30, ['abc'], 100] print(B) # [10, 20, 30, ['abc'], 100] print(C) # [10, 20, 30, ['abc']] print(D) # [10, 20, 30, ['abc', '123']]
memory management
Memory management is divided into memory development and release
1. The development of memory. When using data, apply for memory in the heap, and the value corresponds to the name in the stack
All types in Python are classes, all data are objects, and all data is stored in the heap
When the heap saves data, only one copy of the same immutable data is saved
Save multiple copies of the same variable data
2. Garbage collection mechanism for memory release
Whether a data in Python memory is released depends on the number of references of this data in the program
If it is greater than 0, it will not be destroyed, otherwise it will be destroyed
print(type(10)) a = 100 age = 100 list1 = [100, 200] print(id(a), id(age), id(list1[0])) a = [10, 20] b = [10, 20] c = [100, [10, 20]] print(id(a), id(b), id(c[-1])) A = 100 del A # B = A # NameError: name 'A' is not defined