Python 的多态笔记

Python的多态实际是通过instance 实现的

class Person:
    def __init__(self, name,age):
        self.name = name
        self.age = age

    def feed_pet(self,pet):
        #isinastance(obj,类)-->判断obj,是不是这个类的对象,或者判断obj是不是该类的子类的对象
        if isinstance(pet, Pet):
            self.pet = pet
            print('可以养')
            print(f'{self.name}喜欢喂养{pet.role},昵称是{pet.nickname}')
        else:
            print('不是宠物类型')

class Pet:
    role='Pet'
    def __init__(self,nickname,age):
        self.nickname = nickname
        self.age = age

    def show(self):
        print(f'{self.nickname} 今年{self.age}岁了')

class Cat(Pet):
    role='Cat'
    def catch_Mouse(self):
        print('抓老鼠')
class Dog(Pet):
    role='Dog'
    def Watch_House(self):
        print('看家高手。。。。')
class Tiger:
    def __init__(self,name):
        self.name = name
        self.age = 1

    def eat(self):
        print('太可怕了,能吃人!!')

#创建对象
cat=Cat('花花',2)
dog=Dog('大黄',3)
p1=Person('lucy',23)
tiger1=Tiger('大老虎')
p1.feed_pet(cat)
p2=Person('pengpeng',24)
p2.feed_pet(tiger1)
p2.feed_pet(dog)

上一篇:学习HTML第二十七天


下一篇:springboot~jpa优雅的处理isDelete的默认值