一.单继承
继承是两个类或多个类之间的父子关系,子类继承了基类的所有公有数据属性和方法,并且可以通过编写子类的代码扩充子类的功能。
继承方法:class 子类名(基类名1,基类名2.…)
class Father:#父类(基类)
def __init__(self,lenth,width):
self.lenth = lenth
self.width = width
def area(self):
area = self.lenth * self.width
return area
class Son(Father):#子类
pass
s = Son(10,20)
print(s.area())#子类可从父类调用方法
二.多继承
实现多个继承套用
class Base:
def play(self):
print('我是你祖宗')
class A(Base):
def play(self):
print("我是祖宗的儿子")
class B(Base):
def play(self):
print('我是祖宗的女儿')
class C(B,A):#谁先继承就用谁
pass
c = C()
c.play()
三.子类对父类方法或参数的修改
1.修改父类方法
class Father: # 父类(基类)
def __init__(self, lenth, width):
self.lenth = lenth
self.width = width
def area(self):
area = self.lenth * self.width
return area
class Son(Father): # 子类
def area(self):#可直接重新定义父类方法
area = self.lenth + self.width
return area
s = Son(10, 20)
print(s.area()) # 子类可从父类调用方法
2.修改父类参数
诺想实现子类对父类参数的修改,则须用super(推荐),或者重新定义参数(无意义)
class Father: # 父类(基类)
def __init__(self, lenth, width):
self.lenth = lenth
self.width = width
def area(self):
area = self.lenth * self.width
return area
class Son(Father): # 子类
def __init__(self, lenth, width):#可以通过super对类的参数重新定义
if lenth == width:
super().__init__(lenth,width)
else:
super().__init__(lenth, width)
print('您输入的参数不构成正方形')
s = Son(10, 1)
print(s.area()) # 子类可从父类调用方法