Python 类的继承

继承是面向对象编程(OOP)的第二大特性。子类继承父类的所有publicprotected数据和方法,极大提高了代码的重用性。

创建的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猫类,它也有namespeed两个属性,同时还有colorgenre两个属性,打印时只需要打印namespeed两个属性就行。

因此,基本可以复用基类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(加菲猫,8is printed                name=加菲猫                speed=8

以上就是基本的继承使用案例,继承要求基类定义的数据和行为尽量标准、尽量精简,以此提高继承的复用性。

登入/注册
卧槽~你还有脸回来
没有账号? 忘记密码?