class Person:
def __init__(self,new_name,weight):
# self.属性=形参
self.name=new_name
self.weight=weight
def __str__(self):
return "我的名字是%s,体重是%.2f公斤" %(self.name,self.weight)
def eat(self):
print("%s是吃货,吃完再减肥" %self.name)
self.weight+=1
def run(self):
print("%s爱跑步,跑步锻炼身体" %self.name)
self.weight-=0.5
person1=Person("小明",75.0)
person2=Person("小美",45.0)
person1.run()
person1.eat()
print(person1)
person2.eat()
person2.run()
print(person2)
被使用的类,应该先开发。
class HouseItem:
def __init__(self,name,area):
self.name=name
self.area=area
def __str__(self):
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
总面积是%.2f
剩余面积是%.2f
家具名称有%s"
% (self.house_type,
self.area,
self.free_area,
self.item_list))
def add_item(self, item):
print("要添加%s" %item)
if item.area>self.free_area:
print("%s的面积太大.无法添加" %item.name)
return
self.item_list.append(item.name)
self.free_area-=item.area
# 创建家具
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)