一个类继承和调用的小代码:
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('花')
来源:https://blog.csdn.net/xiao_liushui/article/details/98885046