Python——类的继承

Python——类的继承

    • 1.继承的实现
    • 2.方法重写
    • 3.Python的多继承

1.继承的实现

Python中继承语法格式如下:

class 子类名(父类名):类的属性类的方法

例 7-11 类的继承示例,子类继承父类方法:

#ex0711.py  类的继承示例,子类继承父类方法
class  Animal:num = 0def __init__(self):print("父类 Animal")def show(self):print("父类 Animal 成员方法")class Cat(Animal):def __init__(self):print("构建子类 Cat")def run(self):print("子类 Cat 成员方法")cat = Cat()
cat.run()   #子类方法
cat.show()  #父类方法

运行结果:

例 7-12 类继承的应用

#ex0712.py  类继承的应用
class Employee:def __init__(self,name="",department="computer",age=20):self.setName(name)self.setDepartment(department)self.setAge(age)def setName(self,name):if type(name)!=str:print("姓名必须是字符")returnself.__name=namedef setDepartment(self,department):if department not in ["computer","communication","electric"]:print("专业必须是computer、communication或electric")returnself.__department=departmentdef setAge(self,age):if type(age)!=int or age>=33 or age<20:print("年龄必须是数字,且界于20至33之间")returnself.__age=agedef show(self):print("姓名:{} 专业:{} 年龄:{}".format(self.__name,self.__department,self.__age))class ProjectManager(Employee):def __init__(self,name='',department="computer",age=22,title="middle"):Employee.__init__(self,name,department,age)self.setTitle(title)def setTitle(self,title):self.__title=titledef show(self):Employee.show(self)print("职称:{}".format(self.__title))try:emp1=Employee("Rose")emp1.show()pm1=ProjectManager("Mike","electric",26,"high")pm1.setAge(30)pm1.show()
except Exception as ex:print("数据出现错误",ex)

运行结果:

2.方法重写

在继承关系中,子类会自动拥有父类定义的方法。如果父类定义的方法不能满是子类的需求,子类可以按照自己的方式重新实现从父类继承的方法,这就是方法的重写

重写使得子类中的方法覆盖掉跟父类同名的方法,但需要注意,在子类中重写的方法要和父类被重写的方法具有相同的方法名和参数列表

例 7-13 子类重写父类的方法

#ex0713.py 子类重写父类的方法
class  Animal:def __init__(self,isAnimal):self.isAnimal = isAnimaldef run(self):print("父类 Animal 通用的 run()方法")def show(self):print("父类 Animal 的 show() 成员方法")class Cat(Animal):def __init__(self):print("子类的构造方法")def run(self):  #方法重写super().run()   #使用 super() 方法调用父类方法print("子类 Cat 重写 run() 成员方法")ani = Animal(False)
ani.show()
cat = Cat() #子类的构造方法
cat.run()

运行结果:

3.Python的多继承

一个子类存在多个父类的现象称为多继承

Python 语言是支持多继承的,一个子类同时拥有多个父类的共同特征,即子类继承了多个父类的方法和属性。

扩展:
java不支持多继承,只支持单继承(即一个类只能有一个父类)。但是java接口支持多继承,即一个子接口可以有多个父接口。(接口的作用是用来扩展对象的功能,一个子接口继承多个父接口,说明子接口扩展了多个功能,当类实现接口时,类就扩展了相应的功能)。

多继承是在子类名称后的括号中标注出要继承的多个父类,并且多个父类之间使用逗号分隔,其语法格式如下:

class 子类(父类1,父类2,···):类的属性类的方法

例 7-14 多继承示例

#ex0714.py  多继承示例
class Phone:    #电话类def receive(self):#接收print("接电话")def send(self):#发送print("打电话")class Message:  #消息类def reveive_Msg(self):print("接收信息")def send_Msg(self):print("发送短信")class Mobile(Phone,Message):    #手机类pass    #空语句mobile = Mobile()
mobile.receive()
mobile.send()
mobile.reveive_Msg()
mobile.send_Msg()

运行结果:

本文链接:https://my.lmcjl.com/post/5516.html

展开阅读全文

4 评论

留下您的评论.