面向对象的另一个特性是继承,继承可以更好的代码重用。
例如一个学校里面的成员有老师、学生。老师和学生都有共同的属性名字和年纪。但老师还有它自己的属性,如工资。学生也有它的属性,如成绩。
因此我们可以设计一个父类:SchoolPeople,两个子类:Teacher、Student。
代码如下:
SchoolPeople父类:
1 2 3 4 5 6 7 | class SchoolPeople(): def __init__( self ,name,age): print "Init ShoolPeople" self .name = name self .age = age def tell( self ): print "name is %s,age is %s" % ( self .name, self .age) |
Teacher子类:重写了父类的tell方法。
1 2 3 4 5 6 7 8 | class Teacher(SchoolPeople): def __init__( self ,name,age,salary): SchoolPeople.__init__( self ,name,age) self .salary = salary print "Init teacher" def tell( self ): print "salary is %d" % self .salary SchoolPeople.tell( self ) |
Student子类:没有重写父类的方法
1 2 | class Student(SchoolPeople): pass |
调用:
1 2 3 4 5 | t = Teacher( "t1" , 35 , 10000 ) t.tell() print "\n" s = Student( "s1" , 10 , 95 ) s.tell() |
结果:
Init ShoolPeople
Init teacher
salary is 10000
name is t1,age is 35
Init ShoolPeople
name is s1,age is 10
结果分析:虽然子类Student子类没有具体的实现代码,默认会调用父类的初始化函数和tell方法。
子类Teacher重写了父类的tell方法,所以,他的实例会运行Techer类的tell方法。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?