程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python furniture placement exercise

編輯:Python

demand :

1、 There are different types of houses , List of total area and furniture names
The new house doesn't have any furniture
2、 The furniture has a name and an area , among
The bed : Occupy 4 Square meters
Wardrobe : Occupy 2 Square meters
table : Occupy 1.5 Square meters
3、 Add these three pieces of furniture to the house
4、 When you print the house , Request output ; House type , Total area 、 The remaining area 、 List of furniture names

The analysis process

After reading the requirements, we find that there are two classes in the requirements , One is house , One is furniture , among A new house Is an instantiated object of the house class , And bed 、 Wardrobe 、 The dining table is an instantiated object of the furniture class , Add furniture 、 Printing house information is a function in the house class / Method .

 Houses
attribute :
House type
Total area
The remaining area
List of furniture names
Method :
Add furniture
house info
Furniture :
attribute :
name
Covers an area of

Code display

# Houses 
class House():
# Construction method , Defines the house type 、 Properties of total area 
def __init__(self,huxing,sum_area):
self.huxing = huxing
self.sum_area = sum_area
self.left_area = sum_area # The initial state , The remaining area of the house is the total area of the house 
self.f_list = [] # The initial state , The furniture in the house is empty 
# How to add furniture 
def add_furniture(self, obj): # obj Is the furniture instantiation object added 
self.f_list.append(obj.name) # Furniture instantiation object name attribute 
print(" Added furniture ",obj.name)
self.left_area -= obj.area
print(" The remaining area :",self.left_area)
# Format output - Print house information 
def info(self):
print(''' House type {} The total area of the house {} The house was furnished {} Remaining area of house {}'''.format(self.huxing,self.sum_area,self.f_list,self.left_area))
# Furniture 
class Furniture():
# Construction method , Defines the name and floor area of the furniture 
def __init__(self, name, area):
self.name = name
self.area = area
# The instantiated object of the house newH 
newH = House(" Three rooms and one hall ",130)
# Instantiated object of furniture bed
bed = Furniture("bed",2)
# Instantiated object of furniture desk
desk = Furniture("desk",1.8)
# Instantiated object of furniture wardrobe
wardrobe = Furniture("wardrobe",3)
# Add furniture 
newH.add_furniture(bed)
newH.add_furniture(desk)
newH.add_furniture(wardrobe)
# Print house information 
newH.info()

Running results


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved