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

[Python] introduction of class concept for beginners -- adding furniture

編輯:Python

Example of adding furniture to a house

It's hard to avoid getting dizzy when learning object-oriented for the first time , I hope this quotation can help you .

Add furniture to the house , According to the floor area of furniture , Judge whether the furniture can be added , Add it if you can , The remaining area of the house becomes smaller , Furniture name goes into furniture list , Otherwise, it directly indicates that the area is too large , Unable to add .

Code:

class HouseItem:
""" Create a furniture class """
def __init__(self, name, area):
self.name = name
self.area = area
def __str__(self):
return "[%s] area is %.2f" % (self.name, self.area)
class House:
""" Create a house class """
def __init__(self, house_type, area):
self.house_type = house_type
self.area = area
self.free_area = area # The remaining area 
self.item_list = [] # List of furniture names 
def __str__(self):
return ("House type:%s\narea is %.2f[free: %.2f]\nhouseitem: %s"
% (self.house_type, self.area, self.free_area, self.item_list))
def add_item(self, item):
""" Add furniture functions """
print("Add %s" % item)
# Judge the furniture area 
if item.area > self.free_area:
print("%s area is too large,unable to add" % item.name)
return
# Add furniture to the list 
self.item_list.append(item.name)
# Calculate the remaining area 
self.free_area -= item.area
# Reference furniture ( Create furniture objects )
bed = HouseItem("bed", 20)
chest = HouseItem("chest", 5)
table = HouseItem("table", 100)
print(bed)
print(chest)
print(table)
# Create a house object 
my_home = House("Two rooms and one hall", 60)
my_home.add_item(bed)
my_home.add_item(chest)
my_home.add_item(table)
print(my_home)

Picture:


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