首页 > 编程语言 > 详细

Python类的多态

时间:2021-03-09 11:18:39      阅读:29      评论:0      收藏:0      [点我收藏+]

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))

Python类的多态

原文:https://www.cnblogs.com/codegzy/p/14504220.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!