python面向对象封装

宿舍 2019-10-22

# 面向对象封装案例:为新房子增添家具# 分析对象的属性# 房子属性:户型、面积
# 家具属性: 家具名称、占地面积


class Furniture:

    def __init__(self, name, area):
        self.name = name
        self.area = area

    def __str__(self):
        return F"[{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.furnitures = []

    def __str__(self):
        return F"房子户型:{self.house_type}\n占地面积:{self.area}平方米\n家具包含:{self.furnitures}\n剩余面积:{self.free_area}"

    def add(self, furniture):

        if self.free_area < furniture.area:
            return
        self.furnitures.append(furniture.name)
        self.free_area -= furniture.area


# 创建房子对象
my_house = House("一室一厅", 60)
# 创建家具对象
bed = Furniture("席梦思", 11)
chair = Furniture("实木椅", 0.5)
# 为房子添加家具
my_house.add(bed)
my_house.add(chair)
print(my_house)

输出:

房子户型:一室一厅
占地面积:60平方米
家具包含:[‘席梦思‘, ‘实木椅‘]
剩余面积:48.5

相关推荐