继承是面向对象编程(OOP)的第二大特性。子类继承父类的所有public
和protected
数据和方法,极大提高了代码的重用性。
创建的Animal
类为:
class Animal():
cprop = "我是类上的属性cprop"
def __init__(self,name,speed):
self.name = name # 动物名字
self.__speed = speed # 动物行走或飞行速度
def __str__(self):
return '''Animal({0.name},{0.__speed}) is printed
name={0.name}
speed={0.__speed}'''.format(self)
现在有个新的需求,要重新定义一个Cat
猫类,它也有name
和speed
两个属性,同时还有color
和genre
两个属性,打印时只需要打印name
和speed
两个属性就行。
因此,基本可以复用基类Animal
,但需要修改__speed
属性为受保护(protected
)的_speed
属性,这样子类都可以使用此属性,而外部还是访问不到它。
综合以上,Cat
类的定义如下:
class Cat(Animal):
def __init__(self,name,speed,color,genre):
super().__init__(name,speed)
self.color = color
self.genre = genre
首先使用super()
方法找到Cat
的基类Animal
,然后引用基类的__init__
方法,这样复用了基类的此方法。
使用Cat
类,打印时,又复用了基类的 __str__
方法:
jiafeimao = Cat('加菲猫',8,'gray','CatGenre')
print(jiafeimao)
打印结果:
Animal(加菲猫,8) is printed
name=加菲猫
speed=8
以上就是基本的继承使用案例,继承要求基类定义的数据和行为尽量标准、尽量精简,以此提高继承的复用性。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。