类的继承允许一个类(子类)获取另一个类(父类)的属性和方法。
通过继承,子类可以重用父类的代码,并且可以在此基础上添加自己的特定属性和方法,从而实现代码的复用和扩展。
在类的继承中,父类通常包含一些通用的属性和方法,而子类可以继承这些通用的特性。
类的继承使得代码更具有灵活性和可维护性。在继承链中,子类可以继承父类的属性和方法,而父类本身也可以是其他类的子类,从而形成多层次的继承关系。
类的继承方式分为单继承和多继承。
单继承是一个子类只继承一个父类,多继承是一个子类继承多个父类。
单继承:
一个类可以通过在类定义时在括号中指定父类来实现单继承。
举例:
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print("I can talk")
class Student(Person):
def __init__(self, name, student_id):
super().__init__(name)
self.student_id = student_id
def talk(self):
super().talk()
print("I can read")
s = Student('王皓',10)
print(s.name)
print(s.student_id)
s.talk()
输出:
王皓
10
I can read
I can talk
多继承:
一个类可以通过在类定义时在括号中指定多个父类来实现多继承,多个父类之间使用逗号分隔。
class Person:
def __init__(self, name):
self.name = name
def write(self):
print("I can write")
class AIRobot:
def __init__(self, type):
self.type = type
def code(self):
print("I can code")
class Developer(Person ,AIRobot):
def __init__(self, name, type):
# 两个父类中有同样的方法,子类拿来用时,需要指定父类,写法如下
Person.__init__(self,name)
AIRobot.__init__(self,type)
# 只有其中一个父类有的方法,子类也可以使用super()方法调用父类方法
def write(self):
super().write()
print("I can write a ppt")
#当子类中存在和父类同样的方法名时,子类的方法会覆盖父类的方法,也就是重写机制
def code(self):
super().code()
print("i am codinghaha")
d = Developer(name='王皓',type='统一领吗')
print(d.name)
print(d.type)
d.write()
d.code()
输出:
王皓
统一领吗
I can write
I can write a ppt
I can code
i am codinghaha