程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes 18- inheritance & function rewriting

編輯:Python

One 、 Inherit 【 Focus on mastering 】

1. Concept

If two or more classes have the same properties and methods , We can extract a class , Declare the common parts of each class in the extracted class

 Extracted classes —— Parent class 【father class】 Superclass 【super class】 Base class 【base class】
Two or more classes —— Subclass Derived class
The relationship between them —— Subclass Inherited from Parent class perhaps Parent class Derived Subclass
# Parent class 【Father】、 Superclass 【Super】、 Base class 【Base】
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print("eating")
# Subclass 、 Derived class
class Student(Person):
def __init__(self,name,age,type):
self.type = type
def study(self):
print("studying")
class Worker(Person):
def __init__(self,name,age,kind):
self.kind = kind
def work(self):
print("working")
class Doctor(Person):
pass
class Teacher(Person):
def teach(self):
print("teaching")
"""
summary :
1. If you want to implement inheritance , When defining subclasses ,class Subclass class name ( Parent class name )
2.object Is the root class of all classes
3. After using inheritance , It simplifies the code
4. In addition to inheriting the contents of the parent class , You can also have your own unique properties and methods , It is easy to expand
"""

2. Single inheritance

2.1 Basic use

Simply speaking , A subclass has only one parent , It is called single inheritance

grammar :

class Subclass class name ( Parent class name ):

 The class body

Be careful :object yes Python The root class of all classes in

By default , If a class does not specify the inherited parent class , Inherit from by default object

# Parent class 【Father】、 Superclass 【Super】、 Base class 【Base】
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print("eating")
# Subclass 、 Derived class
class Doctor(Person):
pass
# 1. Be careful 1: If the constructor is not defined in the subclass , Create subclass objects , The constructor in the parent class is called by default , So you need to match the parent class __init__ Pay attention to the matching of parameters
d = Doctor(" Dr. Zhang ",30)
d.eat()
print(d.name,d.age)
# Be careful 2: Subclasses can inherit properties and functions that are not privatized in the parent class
# 2.
class Teacher(Person):
def teach(self):
print("teaching")
t = Teacher(" Teacher wang ",40)
t.eat()
t.teach()
# 3. Be careful 3: If a constructor is defined in a subclass , When you create a subclass object , The constructor in the subclass is called
class Student(Person):
def __init__(self,type):
self.type = type
def study(self):
print("studying")
s = Student(" middle school student ")
print(s.type)
s.eat()
s.study()
# 4. in application , Common cases 【 Focus on mastering 】
# Be careful 4: If a constructor is defined in a subclass , You need to inherit the attributes in the parent class , And define the unique attributes ,
# You need to call the constructor in the parent class in the constructor of the child class
class Worker(Person):
def __init__(self,name,age,kind):
# Mode one :super( The current class ,self).__init__( Property list )
# super(Worker, self).__init__(name,age)
# Mode two :super().__init__( Property list )
# super().__init__(name,age)
# Mode three : Parent class name .__init__(self, Property list )
Person.__init__(self,name,age)
self.kind = kind
def work(self):
print("working")
w = Worker(' Worker ',25," Electrical appliances ")
print(w.kind)
print(w.name,w.age)
w.eat()
w.work()

2.2 Inherited slots

class Person(object):
__slots__ = ("name","age")
def __init__(self,name,age):
self.name = name
self.age = age
p = Person('aaa',10)
# p.hobby = " Sing a song "
class Student(Person):
pass
s = Student("bbb",20)
print(s.name,s.age)
s.hobby = " dance "
print(s.hobby)
# Conclusion : Restricted binding of attributes defined in the parent class 【__slots__】, It will not be inherited by a subclass , If you also need , You need to set it manually

2.3 Class properties in inheritance

# 1
class Person():
place = " The earth "
class Student(Person):
pass
# Be careful 1: Subclasses can inherit class attributes that are not privatized in the parent class , Use the same as instance properties
print(Person.place)
print(Student.place)
# Be careful 2: If you modify a class attribute through a parent class , The class attributes accessed in the subclass will be modified as they are
Person.place = " Mars "
print(Person.place)
print(Student.place)
# Be careful 3: If you modify class attributes through subclasses 【 From the parent class 】, It has no effect on class properties accessed in the parent class
Student.place = " Space "
print(Person.place)
print(Student.place)
# 2.【 Interview questions 】
class A():
x = 1
class B(A):
pass
class C(A):
pass
print(A.x,B.x,C.x) # 1 1 1
A.x = 2
print(A.x,B.x,C.x) # 2 2 2
B.x = 3
print(A.x,B.x,C.x) # 2 3 2

3. Multiple inheritance

seeing the name of a thing one thinks of its function , Multiple inheritance means that a subclass can have multiple parent classes , such as : A child has a father , A mother

grammar :

class Subclass ( Parent class 1, Parent class 2, Parent class 3....):

 The class body

Be careful :object Is the root class of all classes

# 1.
class Runnale(object):
def run(self):
print("running")
class Flyable(object):
def fly(self):
print("flying")
# Single inheritance
class Dog(Runnale):
pass
# Multiple inheritance
class Bird(Runnale,Flyable):
pass
# 2.
class Father(object):
def __init__(self,money):
self.money = money
def play(self):
print("playing")
def show(self):
print("father~~~~show")
class Mother(object):
def __init__(self,face_value):
self.face_value = face_value
def eat(self):
print("eating")
def show(self):
print("mother~~~~show")
# a.
class Child1(Mother,Father):
pass
# Be careful 1: Constructor not defined in subclass , When creating a subclass object , The constructor in the first parent class in the parent class list is called by default
# c1 = Child1(10)
# print(c1.face_value)
# b.
class Child2(Mother,Father):
def __init__(self,money,face_value,hobby):
# Be careful 2: Same as single inheritance , If you need to use the instance property in the parent class in the child class , Call the constructor in the parent class in the constructor of the child class
# Be careful 3: Call the constructor in the parent class in the constructor of the child class , Use super() Can only call the constructor in the first parent class in the parent class list
# If all the constructors of the parent class need to call , Only use Parent class name .__init__(self, Property list )
Father.__init__(self, money)
Mother.__init__(self, face_value)
self.hobby = hobby
def study(self):
print("studying")
# Extensibility
def show(self):
# super().show() # Only the functions in the first parent class in the parent class list will be called
Father.show(self)
Mother.show(self)
print("child~~~~~show")
c2 = Child2(13,45,' running ')
c2.play()
c2.eat()
c2.study()
print(c2.money,c2.face_value,c2.hobby)
# Be careful 4: If a function with the same name appears in multiple parent classes , When subclass objects are called , By default, the function in the first parent class in the parent class list is called
c2.show()

4. The characteristic of multiple inheritance

Two 、 Function rewriting 【 Focus on mastering 】

"""
Function rewriting :override
Premise : In the case of inheritance
Use : If the function in the parent class is re implemented in the child class , This process is called function rewriting
Criteria of judgment : As long as a function with the same name as that in the parent class appears in the child class , let me put it another way , The declaration of a function in a subclass is exactly the same as that of a function in a parent class , Is to rewrite ,
"""
# 1. Override of custom functions
# a
class Person():
def func(self):
print(" Parent class ~~~~func")
class Child(Person):
pass
c = Child()
c.func()
# b
class Person():
def func(self):
print(" Parent class ~~~~func")
class Child(Person):
def func(self):
print(" Subclass ~~~~func")
c = Child()
c.func()
# c. Be careful : When a parent class has multiple subclasses , The functions implemented in the parent class meet the needs of most child classes , Only a few subclasses cannot be used ,
# You can re implement the specified function in the parent class in the child class
class Animal():
def walk(self):
print(" Walking on the ground ")
class Dog(Animal):
pass
class Cat(Animal):
pass
class Bird(Animal):
def walk(self):
print(" Flying in the sky ")
class Elephant(Animal):
pass
# 2. Rewriting of system functions
# a.
class Person1(object):
def __init__(self,name,age):
self.name = name
self.age = age
# By default , When printing objects , Would call object Medium __str__(), By default, this function returns a string representing the address of the current object
p1 = Person1(' Zhang San ',10)
print(p1)
print(p1.__str__())
# b.
class Person2(object):
def __init__(self,name,age):
self.name = name
self.age = age
# If you want to print objects , The result is the property information of the current object , You need to override... In subclasses __str__,
# This function can only return one string , Therefore, it is recommended to format the attribute information of the object into a string to return
def __str__(self):
return f" full name :{self.name}, Age :{self.age}"
# def __repr__(self):
# return f" full name :{self.name}, Age :{self.age}"
__repr__ = __str__
p2 = Person2(' Zhang San ',10)
print(p2)
# print(p2.__str__())
# If an object exists as an element in an iteratable object such as a list , Print iteratable objects directly , By default , The object still appears as an address
# If you also need to display attribute information in the list , You need to rewrite __repr__
list1 = [p2]
print(list1)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved