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("%s爱跑步" % self.name)
self.weight -= 0.5
def eat(self):
print("%s是吃货" % self.name)
self.weight += 0.5
xiaoming = Person("小明", 75)
xiaoming.run()
xiaoming.eat()
print(xiaoming)
xiaomei = Person("小美", 50)
xiaomei.run()
xiaomei.eat()
print(xiaomei)
#####################################
class HouseItem:
def __init__(self,name,area):
self.name=name
self.area=area
def __str__(self):# 用于print(对象)时输出数据
return "[%s]占地 %.2f平米"%(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):
if item.area>self.free_area:
print("%s 面积过大,无法添加" % item.name)
return
self.item_list.append(item.name)
self.free_area-=item.area
print("要添加 %s "% item)
bed=HouseItem("席梦思",40)
chest=HouseItem("衣柜",20)
table=HouseItem("餐桌",1.5)
print(bed)
print(chest)
print(table)
my_home=House("两室一厅",60)
my_home.add_item(bed)
my_home.add_item(chest)
my_home.add_item(table)
print(my_home)
class Gun:
def __init__(self, model):
self.model = model
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count += count
def shoot(self):
if self.bullet_count <= 0:
print("[%s]没有子弹了" % self.model)
return
self.bullet_count -= 1
print("[%s]突突突...[%d]" % (self.model, self.bullet_count))
class Soldier:
def __init__(self,name):
self.name=name
self.gun=None
def fire(self):
if self.gun is None:
print("%s没有枪"% self.name)
return
self.gun.add_bullet(50)
self.gun.shoot()
ak47 = Gun("AK47")
xusanduo=Soldier("许三多")
xusanduo.gun=ak47
xusanduo.fire()