應(yīng)用:存放家具
#定義一個(gè)home類
classHome:
def__init__(self, area):
self.area = area#房間剩余的可用面積
#self.light = 'on' #燈默認(rèn)是亮的
self.containsItem = []
def__str__(self):
msg ="當(dāng)前房間可用面積為:"+ str(self.area)
iflen(self.containsItem) >0:
msg = msg +"容納的物品有: "
fortempinself.containsItem:
msg = msg + temp.getName() +", "
msg = msg.strip(", ")
returnmsg
#容納物品
defaccommodateItem(self,item):
#如果可用面積大于物品的占用面積
needArea = item.getUsedArea()
ifself.area > needArea:
self.containsItem.append(item)
self.area -= needArea
print("ok:已經(jīng)存放到房間中")
else:
print("err:房間可用面積為:%d,但是當(dāng)前要存放的物品需要的面積為%d"%(self.area, needArea))
#定義bed類
classBed:
def__init__(self,area,name ='床'):
self.name = name
self.area = area
def__str__(self):
msg ='床的面積為:'+ str(self.area)
returnmsg
#獲取床的占用面積
defgetUsedArea(self):
returnself.area
defgetName(self):
returnself.name
#創(chuàng)建一個(gè)新家對(duì)象
newHome = Home(100)#100平米
print(newHome)
#創(chuàng)建一個(gè)床對(duì)象
newBed = Bed(20)
print(newBed)
#把床安放到家里
newHome.accommodateItem(newBed)
print(newHome)
#創(chuàng)建一個(gè)床對(duì)象
newBed2 = Bed(30,'席夢(mèng)思')
print(newBed2)
#把床安放到家里
newHome.accommodateItem(newBed2)
print(newHome)
總結(jié):
·如果一個(gè)對(duì)象與另外一個(gè)對(duì)象有一定的關(guān)系,那么一個(gè)對(duì)象可用是另外一個(gè)對(duì)象的屬性