面向对象 第三部分 继承和多态

继承的示例:

class
Animal(object):# 父类 def run(self): print('Animal is running...') class Dog(Animal): def run(self):# 狗类 继承了 动物类 print('Dog is running...') def eat(self): print('Eating meat...') class Cat(Animal):# 猫类 继承了 动物类 def run(self): print('Cat is running...') # 实例化dog dog= Dog() dog.run() # 实例化cat cat= Cat() cat.run() # 判断类型 a=list() # a是list类型 b=Animal()# b是Animal类型 c=Dog()# c是Dog类型 result1=isinstance(c,Dog) print(result1) result2=isinstance(c,Animal)# c属于dog,也属于父类 print(result2)

 

多态的示例:obj.fly()方法 有多种状态来自3个类,每个类中都有各自的fly()

class Bird:
    def fly(self):
        print("鸟在天上飞翔")
class Plane:
    def fly(self):
        print("飞机在天上飞")
class Rocket:
    def fly(self):
        print("火箭冲上太空")
# 定义一个方法,但有多种状态地飞
def fly(obj):
    obj.fly()
# 实例化对象
bird=Bird()
plane=Plane()
rocket=Rocket()
# 调用fly方法
fly(bird)
fly(plane)
fly(rocket)

 

posted @ 2023-07-14 16:58  胖豆芽  阅读(2)  评论(0编辑  收藏  举报