宠物商店 继承关系

泪湿孤枕 提交于 2019-11-26 14:27:10

一个类继承和调用的小代码:

class PetShop:
    def __init__(self, name):
        self.name = name
        self.pets = set()

    # 动作
    def save_pet(self, pet):
        # print(isinstance(pet, Pet))
        if isinstance(pet, Pet):
            self.pets.add(pet)
            print('添加成功!')
        else:
            print('不是宠物不收留!')

def sale_pet(self, pet):
    if isinstance(pet, Pet):
        self.pets.discard(pet)
        print('宠物减少')
    else:
        print('不是宠物不收留!')

# 查找宠物
def search_pet(self, pname):
    for pet in self.pets:
        if pname == pet.pname:
            print('宠物在商店里')
            break
    else:
        print('不存在此宠物!')

# 显示所有的宠物
def all_

pets(self):
        print('宠物商店所有的宠物信息如下:')
        for pet in self.pets:
            print(pet)


class Pet:
    type = '宠物'

    def __init__(self, pname, color, age):
        self.p

name = pname
            self.color = color
            self.age = age

    def __str__(self):
        return '当前类型是:{},宠物名:{}'.format(self.type, self.pname)


class Dog(Pet):
    type = '狗'
    
        def see_house(self):
            print('特长看家...')
    
    
    class Cat(Pet):
        type = '猫'
    
        def catch_mouse(self):
        print('特长抓老鼠....')


class Bird:
    pass

创建对象

shop = PetShop('爱宠')

# pet = Pet()
cat = Cat('花花', '黄色', 2)
bird = Bird()
shop.save_pet(cat)  # pet =cat
dog = Dog('大黄', '棕色', 3)
shop.save_pet(dog)

shop.all_pets()

shop.search_pet('花')
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!