python类的继承机制
继承是面向对象的三大特征之一,也是实现代码复用的重要手段。继承经常用于创建和现有类功能类似的新类,又或是新类只需要在现有类基础上添加一些成员(属性和方法),但又不想直接将现有类代码复制给新类。
python中,实现继承的类称为子类,被继承的类称为父类(也可称为基类、超类)。子类继承父类的语法是:在定义子类时,将多个父类放在子类之后的圆括号里。语法格式如下:
class类名(父类1,父类2,...):
#类定义部分
注意,Python的继承是多继承机制,即一个子类可以同时拥有多个直接父类。
下面程序示范了子类继承父类的特点。下面是Fruit类的代码:
classFruit:
definfo(self):
print("我是一个水果!重%g克"%self.weight)
classFood:
deftaste(self):
print("不同食物的口感不同")
#定义Apple类,继承了Fruit和Food类
classApple(Fruit,Food):
pass
#创建Apple对象
a=Apple()
a.weight=5.6
#调用Apple对象的info()方法
a.info()
#调用Apple对象的taste()方法
a.taste()
运行结果为:
我是一个水果!重5.6克
不同食物的口感不同
上面程序中,定义了两个父类:Fruit类和Food类,接下来定义了一个Apple类,该类本身是空类,但其继承自Food类和Fruit类。因此,在主程序部分创建了Apple对象之后,可以访问Apple对象的info()和taste()方法,这表明Apple对象也具有了info()和taste()方法,这就是继承的作用,即子类扩展(继承)了父类,将可以继承得到父类定义的方法,这样子类就可复用父类的方法了。
以上内容为大家介绍了Python培训之类的继承机制,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






