Inheritance
Inheritance is a way to create new classes. In python, new classes can be inherited from one or more parent classes, the original class is called base class or superclass, and the new class is called derived class or subclass.
Class inheritance in python is divided into single inheritance and multiple inheritance
class ParentClass1: #Defining parent classes
pass
class ParentClass2: #Defining parent classes
pass
class SubClass1(ParentClass1): #Single inheritance, base class is ParentClass1,Derivative classes are SubClass1
pass
class SubClass2(ParentClass1,ParentClass2): #python Supporting multiple inheritance, separating multiple inherited classes with commas
pass
Use the'_bases_'method to view inheritance
>>> SubClass1.__bases__
(<class '__main__.ParentClass1'>,)
>>> SubClass2.__bases__
(<class '__main__.ParentClass1'>, <class '__main__.ParentClass2'>)
Tip: If no base class is specified, python's class will inherit the object class by default. Object is the base class of all Python classes. It provides some common methods (such as _str_) implementation.
>>> ParentClass1.__bases__
(<class 'object'>,)
>>> ParentClass2.__bases__
(<class 'object'>,)
Inheritance and abstraction (first abstraction and then inheritance)
Abstraction is the extraction of similar or more similar parts. It is a method of classification.
The abstraction is divided into two levels:
1. Classify the parts that are similar to Obama and Messi;
2. it is a comparison between the three parts of human, pig and dog.
The main role of abstraction is to categorize (to isolate concerns and reduce complexity)
Inheritance: It is based on the result of abstraction. To realize it through programming language, we must go through the process of abstraction before we can express the abstract structure through inheritance.
Abstraction is only an action or a skill in the process of analysis and design, through which classes can be obtained.
Inheritance and reuse
In developing programs, if we define a class A and then want to create another class B, but most of the content of class B is the same as class A, we can not write a class B from scratch, which uses the concept of class inheritance.
Class B is created by inheritance, so that B inherits all attributes of A (data attributes and function attributes) and realizes code reuse.
class A:
def test(self):
print('test function')
class B(A): #New Class B Inheritance class A,class A All attributes in the B inherit
pass
b1 = B() #class B Instances can refer to parent classes B Of'test'Method
b1.test()
#Operation results
#test function
Create a new class with existing classes, which reuses some of the existing software settings and greatly reduces the programming workload, which is often referred to as software reuse. It can not only reuse its own classes, but also inherit others, such as standard libraries, to customize new data types, which greatly shortens the software development cycle and is of great significance to large-scale software development.
Of course, subclasses can also add their own new attributes or redefine these attributes here (without affecting the parent class). It should be noted that once they redefine their own attributes and rename them with the parent class, then they call the new attributes on their own.
class A:
def test(self):
print('test function')
class B(A): #New Class B Inheritance class A,class A All attributes in the B inherit
def test(self):
print('test function B')
pass
b1 = B() #class B Instances can refer to parent classes B Of'test'Method, but there are also renames under its own class'test'Method, with its own priority
b1.test()
#Operation results
#test function B
In subclasses, when editing functions within a function, it may be necessary to reuse the function of the renamed function in the parent class. It should be in the form of calling ordinary functions, that is, class name. func(), which is the same as calling ordinary functions, so even if the self parameter is passed to it.
class A:
def __init__(self, name, age):
self.name = name
self.age = age
def test(self):
print('test function')
class B(A): #New Class B Inheritance class A,class A All attributes in the B inheritpass
b1 = B('jack', 21) #class B Instances can refer to parent classes B Of'test'Method
print(b1.name)
print(b1.age)
b1.test()
#Operation results
#jack
#21
#test function
class A:
def __init__(self, name, age):
self.name = name
self.age = age
def test(self):
print('test function')
class B(A): #New Class B Inheritance class A,class A All attributes in the B inherit
def __init__(self, name, age, country):
A.__init__(self, name, age) #Reference to attributes of parent classes
self.country = country #Increase your own unique attributes
def test(self):
print('test function B')
pass
b1 = B('jack', 21, 'China') #class B Instances can refer to parent classes B Attributes, if there are renamed attributes, take precedence over attributes of their own classes
print(b1.name)
print(b1.age)
print(b1.country)
b1.test()
#Operation results
#jack
#21
#China
#test function B
4. Combination and reuse
Composition refers to the combination of classes in which objects of another class are used as data attributes.
class Teacher:
def __init__(self, name, gender, course):
self.name = name
self.gender = gender
self.course = course
class Course:
def __init__(self, name, price, period):
self.name = name
self.price = price
self.period = period
course_obj = Course('Python', 15800, '5months') #New Course Objects
#Teachers and Courses
t_c = Teacher('egon', 'male', course_obj) #New Teacher Example, Combination of Course Objects
print(t_c.args.name) #Print out the name of the course given by the teacher
#Operation results
#Python
Combination and inheritance are both important ways to effectively utilize the resources of existing classes, but their concepts and usage scenarios are different.
1. The Way of Inheritance
Through inheritance, the relationship between derived classes and basic classes is established. It is a'yes'relationship, such as white horse is a horse and human is an animal.
When there are many similar functions between classes, it is better to extract these common functions into base classes and inherit them. For example, a professor is a teacher.
>>> class Teacher:
... def __init__(self,name,gender):
... self.name=name
... self.gender=gender
... def teach(self):
... print('teaching')
...
>>>
>>> class Professor(Teacher):
... pass
...
>>> p1=Professor('egon','male')
>>> p1.teach()
teaching
2. The Way of Combination
The relationship between classes and classes of combinations is established in the way of combinations. It is a kind of "yes" relationship, such as professors having birthdays, professors teaching python courses.
class BirthDate:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
class Couse:
def __init__(self,name,price,period):
self.name=name
self.price=price
self.period=period
class Teacher:
def __init__(self,name,gender):
self.name=name
self.gender=gender
def teach(self):
print('teaching')
class Professor(Teacher):
def __init__(self,name,gender,birth,course):
Teacher.__init__(self,name,gender)
self.birth=birth
self.course=course
p1=Professor('egon','male',
BirthDate('1995','1','27'),
Couse('python','28000','4 months'))
print(p1.birth.year,p1.birth.month,p1.birth.day)
print(p1.course.name,p1.course.price,p1.course.period)
#Operation results:
#1 27
#python 28000 4 months
Combination examples:
1 #Composite reuse code 2 class Teacher: 3 def __init__(self, name, sex, args): 4 self.name = name 5 self.sex = sex 6 self.args = args 7 8 class Student: 9 def __init__(self, name, sex, args): 10 self.name = name 11 self.sex = sex 12 self.args = args 13 14 class Course: 15 def __init__(self, name, price, period): 16 self.name = name 17 self.price = price 18 self.period = period 19 20 class Birth: 21 def __init__(self, year, month, day): 22 self.year = year 23 self.month = month 24 self.day = day 25 26 class Score: 27 def __init__(self, score): 28 self.score = score 29 30 def score_grade(self): 31 if self.score > 90: 32 g = 'A' 33 elif self.score > 80: 34 g = 'B' 35 elif self.score > 70: 36 g = 'C' 37 elif self.score > 60: 38 g = 'D' 39 else: 40 g = 'F' 41 return g 42 course_obj = Course('Python', 15800, '5months') #curriculum 43 birth_obj_t = Birth(2000, 4, 19) #Teacher's Birthday 44 birth_obj_s = Birth(2009, 9, 21) #Student's Birthday 45 score_obj = Score(91) #Student Achievements 46 #Teachers and Courses 47 t_c = Teacher('egon', 'male', course_obj) 48 print('%s Teacher and Professor%s' % (t_c.name, t_c.args.name)) #Print out the name of the course given by the teacher 49 #Students and Courses 50 s_c = Student('jack', 'male', course_obj) 51 print('%s Study%s' % (s_c.name, s_c.args.name)) 52 #Teacher and Birthday 53 t_b = Teacher('egon', 'male', birth_obj_t) 54 print('%s Teacher's birthday is:%s year %s month %s day'%(t_b.name, t_b.args.year, t_b.args.month, t_b.args.day)) 55 #Students and Birthdays 56 s_b = Student('jack', 'male', birth_obj_s) 57 print('%s Students'birthdays are:%s year %s month %s day'%(s_b.name, s_b.args.year, s_b.args.month, s_b.args.day)) 58 #Students and scores 59 s_s = Student('jack', 'male', score_obj) 60 print('%s The results of the students are as follows:%s,Grade%s' % (s_s.name, s_s.args.score, s_s.args.score_grade())) 61 62 63 #Operation results: 64 #egon Teacher and Professor Python 65 #jack Study Python 66 #egon Teacher's birthday: 19 April 2000 67 #jack Students'birthday is September 21, 2009 68 #jack The student's score was 91.,Grade A
Reference material:
1. http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label10