面向对象的继承
发布日期:2021-08-17 06:32:57 浏览次数:5 分类:技术文章

本文共 1969 字,大约阅读时间需要 6 分钟。

子类能继承父类的属性和方法,若子类没有,则去父类中调用

1 class People: 2     def __init__(self,name,age,general): 3         self.name=name 4         self.age=age 5         self.general=general 6  7     def zhuanqian(self,money): 8         print('努力工作赚钱%s'%money) 9 class Student(People):10     '学生类继承于人类'11     pass12 13 # print(People.__dict__)14 # print(Student.__dict__)15 s1=Student('xiaolong',21,'man')16 print(s1.general)17 s1.zhuanqian(999)

 通常更常用一些的方法是接口继承,它在父类中定义好子类继承必须具备的函数,但不会提供函数的具体实现,由子类继承后来具体实现,Python可以有多个父类继承,但Java或者C#只能有一个。

1 import abc 2 class About(metaclass=abc.ABCMeta): 3     @abc.abstractmethod  4     def read(self): 5         pass 6  7     @abc.abstractmethod 8     def write(self): 9         pass10 11 class Disk(About):12     def read(self):13         print('disk read')14     def write(self):15         print('disk write')16 17 class Cd(About):18     def read(self):19         print('cd read')20     def write(self):21         print('cd write')22 23 24 d1=Disk()25 d1.read()26 d1.write()

 对父类的字段属性进行调用,同时衍生出子类特有的字段属性,可以直接在子类初始化字段属性时,直接父类调用初始化属性(子类self的init方法一定得包含父类的属性)

1 class Vehicle: 2     '这是一个交通工具类' 3     def __init__(self,name,speed,price,many): 4         self.name=name 5         self.speed=speed 6         self.price=price 7         self.many=many 8  9     def run(self):10        print('****************%s准备发车了,速度是%s' % (self.name, self.speed))11 12 class Bus(Vehicle):13     '这是一个公汽 子类'14     def __init__(self,name,speed,price,many,num,addres):15         # Vehicle.__init__(self,name,speed,price,many) super().__init__(name,speed,price,many)16         self.num=num17         self.addres=addres18 19     def run(self):20         print('%s第%s线启动了,请%s的旅客做好准备!'%(self.name,self.num,self.addres))21         # Vehicle.run(self)   22         super().run()  换成super后可自动匹配父类 并且无需再传入self 灵活度高23 24 b1=Bus('复兴号','200km/h',125,2000,'007号','南京')25 b1.run()

 子类在调用函数的时候优先调用自己的方法,然后再调用父类的函数方法

用super方法后,以后父类若变更类名,依旧可以正常使用

 

 

转载于:https://www.cnblogs.com/wen-kang/p/9236891.html

转载地址:https://blog.csdn.net/weixin_30838921/article/details/98952096 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:xshell连接centOS服务器的简单配置:
下一篇:【2019/3/9】周进度报告

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月08日 10时18分43秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章