用python模拟对象间通信,来了解对象间传递信息的本质。
定义了Water类,Dog类,Cat类。
模拟狗喝水,猫喝水,默认水量Water.amount=100。如果是狗喝水,水量
减少10;如果是猫喝水,水量减少5。
代码如下:
'''以下代码模拟对象间通信'''
#定义Water类
class Water():
def __init__(self,amount=100):
self.amount=amount
def reduce(self,species):
if species=="dog":
self.amount-=10
elif species=="cat":
self.amount-=5
def output(self):
print("现在的水量为:"+str(self.amount))
#定义Dog类
class Dog():
def __init__(self,name,year):
self.name=name
self.year=year
def drink(self,water):
water.reduce("dog")
#定义Cat类
class Cat():
def __init__(self,name,year):