面向对象案例——宠物医院

面向对象实现:宠物生病治疗

分析设计:

宠物:昵称、健康值、恢复
人:昵称、健康值
宠物医院:名字、治疗

class Pet:
	"""定义一个宠物类型"""

	def __init__(self, nickname, health):
		self.nickname = nickname
		self.health = health

	def recovery(self):
		"""定义宠物康复的行为"""
		self.health += 5
		print(self.nickname, "正在恢复中...")


class Person:
	"""定义一个人的类型"""

	def __init__(self, nickname, health):
		self.nickname = nickname 
		self.health = health
	
	def recovery(self):
		"""定义人恢复的行为"""
		self.health += 10
		print(self.nickname, "正在恢复中...")


class PetHospital:
	"""定义宠物医院的类型"""

	def __init__(self, name):
		self.name = name
	
	def treat(self, pet):
		"""定义治疗的行为"""
		# 判断治疗类型是否为宠物
		if isinstance(pet, Pet):
			while pet.health < 65:
				#需要接受治疗
				print("开始接受治疗", pet.nickname)
				#调用宠物康复的方法
				pet.recovery()
			else:
				print(pet.nickname, "已经恢复健康")
		else:
			print(pet.nickname, "我们是宠物医院哦")

		
# 创建对象,接受治疗
pet1 = Pet("哈哈", 55)
person1 = Person("小明", 50)

#创建一个宠物医院,治疗送来的宠物
ph1 = PetHospital("梦之家")

#调用对象行为
ph1.treat(pet1)
ph1.treat(person1)		
				

运行结果:
哈哈 开始接受治疗
哈哈 正在恢复中…
哈哈 开始接受治疗
哈哈 正在恢复中…
哈哈 已经恢复健康
小明 我们是宠物医院哦

猜你喜欢

转载自blog.csdn.net/qq_41828603/article/details/87195011