1. 程式人生 > >Python面向物件練習

Python面向物件練習

#!/usr/bin/python3
#coding=utf8
#Author:HeiTao

#定義房子類
class  Home:
    def __init__(self,type,size,addr):
        self.name=type
        self.size=size
        self.addr=addr
        self.residual_size=size
        self.furniture_list=[]

    def __str__(self):
        msg="位於%s的%s的房子總面積為%s平米" %(self.addr,self.name,self.size)
        msg+="房子剩餘空間為%s,房子裡的傢俱有%s" %(self.residual_size,str(self.furniture_list))
        return msg

    #新增傢俱
    def add_furniture(self,fitment):
        self.residual_size -= fitment.get_size()
        self.furniture_list.append(fitment.get_name())

#傢俱1
class Bed:
    def __init__(self,name,size):
        self.name=name
        self.size=size

    def get_name(self):
        return self.name

    def get_size(self):
        return self.size

fangzi=Home("三室兩廳",150,"北京市-朝陽區-長安街")
#床
bed1=Bed("單人床",2)
fangzi.add_furniture(bed1)
#雙人床
bed2=Bed("雙人床",4)
fangzi.add_furniture(bed2)
print(fangzi)