Python类的多态

Dog和Cat都继承Animal,都使用父类的init方法,但是greet方法却是不同的,子类对父类进行了覆盖,还编写了自己的run方法


class Animal(object):
    def __init__(self,name):
        self.name = name
    def greet(self):
        print('I am a animal')

class Dog(Animal):
    def greet(self):
        print('I am a ' + self.name + ' dog')
    def run(self):
        print('dog run')

class Cat(Animal):
    def greet(self):
        print('I am a ' + self.name + ' cat')
    def run(self):
        print('cat run')


dog = Dog('black')
cat = Cat('white')
dog.greet()
cat.greet()
dog.run()
cat.run()
# isinstance判断某个数据是否是该类型
print(isinstance(dog,Animal))
print(isinstance(cat,Animal))
print(isinstance(dog,Dog))
print(isinstance(dog,Cat))

posted @ 2021-03-09 10:39  code-G  阅读(74)  评论(0编辑  收藏  举报