Python之面向对象编程【小明跑步】、【置办家具】
阅读原文时间:2023年07月08日阅读:1

#!usr/bin/python
2 #encoding=utf-8
3 #-----------------小明跑步-------------
4 #1.小明体重75.0公斤
5 #2.小明每次跑步会减肥0.5公斤
6 #3.小明每次吃东西体重会增加1公斤
7
8
9 class Person(object):
10 def __init__(self, name, weight):
11 self.weight = weight
12 self.name = name
13 def __str__(self):
14 msg = self.name + " 的体重为: " + str(self.weight) + " KG"
15 return msg
16 def run(self, num):
17 self.weight -= 0.5 * num # num表示对象跑步的次数
18 def eat(self, num):
19 self.weight += num # num表示对象吃东西的次数
20
21 xiaoming = Person('xiaoming',75.0)
22 #print ("小明原始体重为: %f"%xiaoming.weight)
23 print(xiaoming)
24 print("--------------------------------------------")
25 xiaoming.run(4)
26 print(xiaoming)
27 print("--------------------------------------------")
28 xiaoming.eat(1)
29 print(xiaoming)

2. 放置家具:

实现输出房间总面积,剩余面积,家里家具列表。

#!usr/bin/python
2 #encoding=utf-8
3 #-------------------------摆放家具---------------------------
4 # 1. 房子有总面积、家具,新房子没有任何家具
5 # 2. 家具有名字和占地面积,需要把家具添加到房子里
6 # 3. 打印房子时,需要输出:房子总面积、剩余面积、家具列表
7
8 #定义房间类
9 class House():
10 flag = 0
11 def __init__(self, area):
12 self.area = area
13 self.remidArea = area
14 self.furniture = [] #房子里家具列表
15 def __str__(self):
16 msg = "房子的总面积为:" + str(self.area) + "平方。"
20 msg = msg + "\n家的剩余面积为:" + str(self.remidArea) + " 平方。\n家里的家具有:"
21 for temp in self.furniture:
22 msg += temp.name + ","
23 msg = msg.strip(",") + "。"
24 return msg

26
27 #定义函数:添加家具到房子
28 def AddFurni(self, item):
29 global flag
30 print("购买了家具:%s,占地面积:%s 平方。"%(item.name,item.area))
if self.remidArea >= item.area :
32 self.furniture.append(item)
33 self.remidArea -= item.area
34
35 else:
36 # flag =1
37 print ("房子面积不足以容纳该家具!")
42
43 #定义家具类
44 class Furniture():
45 def __init__(self, name, area):
46 self.name = name #家具名称
47 self.area = area
48
49 print("----------------------第一次------------------------")
50 myHouse = House(160)
51 bed = Furniture("床",25)
52 myHouse.AddFurni(bed)
53 print(myHouse)
54 print("----------------------第二次------------------------")
55 desk = Furniture("书桌",5)
56 myHouse.AddFurni(desk)
57 print(myHouse)
58 print("----------------------第三次------------------------")
59 sofa = Furniture("沙发",100)
myHouse.AddFurni(sofa)
61 print(myHouse)
62 print("----------------------第四次------------------------")
63 fridge = Furniture("冰箱",50)
64 myHouse.AddFurni(fridge)