封装是根据职责将属性和方法 封装到一个抽象的类中。
下面是我在学习中的练习案例:
1.小明爱跑步
class Person: def __init__(self,name,weight): self.name = name self.weight = weight def __str__(self): return "我的名字是%s,我的体重是%.2f" % (self.name,self.weight) def run(self): print("feizhu") self.weight -= 0.5 def eat(self): print("miaotiao") self.weight += 1 xiaoming = Person("小明",85.0) xiaoming.run() xiaoming.eat() print(xiaoming) xiaomei = Person("小妹",60) xiaomei.run() xiaomei.run() print(xiaomei)
2.摆放家具
''' 需求: 1.房子有户型、总面积和家具名称列表 2.家具有名字和占地面积 其中,床占地4平米,衣柜占地2平米,桌子占地1.5平米 3.将以上三件家具添加到房子中 ''' class HouseItem: def __init__(self,name,area): self.name = name self.area = area def __str__(self): return "[%s]占地%.1f平米" % (self.name,self.area) class House: def __init__(self,house_type,area): self.house_type = house_type self.area = area self.free_area = area self.item_list = [] def __str__(self): return ("户型:%s\n总面积:%.2f[剩余面积:%.2f]\n家具:%s" % (self.house_type,self.area,self.free_area,self.item_list)) def add_item(self,item): print("添加:%s" % item) self.free_area = self.free_area - item.area self.item_list.append(item.name) #1.创建家具对象 bed =HouseItem("床",4) chest = HouseItem("衣柜",2) table = HouseItem("桌子",1.5) print(bed) print(chest) print(table) #2.创建房子对象 my_home = House("两室",60) my_home.add_item(bed) my_home.add_item(chest) my_home.add_item(table) print(my_home)
3.士兵突击
''' 需求: 1.士兵许三多有一把AK47 2.士兵可以开火 3.枪能够发射子弹 4.枪能装填子弹---增加子弹数量 ''' #创建一个gun类 class Gun: def __init__(self,model): self.model = model self.count = 0 def add_count(self,count): self.count += count def shoot(self,times): self.times = times #1.判断子弹的数量 if self.count <times: print("%s子弹不够,剩余%d发" % (self.model,self.count)) return #2.发射子弹 self.count -= self.times print("%s突突突[子弹剩余:%d发]" % (self.model,self.count)) #创建一个士兵类 class Soldier: def __init__(self,name): self.name = name self.gun = None #定义开火的方法 def fire(self): #1.判断士兵是否有枪 if self.gun ==None: print("%s没有枪" % self.name) return #2.喊口号 print("%s冲鸭!!!" % self.name) #3.装子弹 self.gun.add_count(50) #4.发射子弹 self.gun.shoot(2) #创建枪对象 ak47 = Gun("AK47") #创建士兵对象 xusanduo = Soldier("许三多") #给士兵分配一把枪 xusanduo.gun = ak47 xusanduo.fire() print(xusanduo)