继承实例--一个房屋中介

通过一个房屋中介的实例,说明继承

*实现的功能:
- 中介掌握有所有房屋的信息
- 中介可以添加房屋,在他掌握的房屋信息中
- 房子有两种类型,有区分*

class Agent:
    # 代理类
    Property_list = []
    def display(self):
        # 通过循环呈现出所有的房产
        for each_property in self.Property_list:
            each_property.display()

    def create_property(self, name):
        # 一个代理可以创建一个新的房产在他的房产列表里面
        num_washroom = input("num_washroom:")
        area = input("area:")
        num_bedroom = input("num_bedroom:")
        if "Apartment" in name:
            balcony = input("balcony:")
            new_Apartment = ApartmentProperty(name=name, area=area,
                                              num_bedroom=num_bedroom,
                                              num_washroom=num_washroom,
                                              balcony=balcony)
        else:
            num_warehouse = input("num_warehouse:")
            garage = input("garage:")
            new_House = HouseProperty(name=name, area=area,
                                      num_bedroom=num_bedroom,
                                      num_washroom=num_washroom,
                                      num_warehouse=num_warehouse,
                                      garage=garage
                                      )

class Property:
    def __init__(self, name='', area='', num_bedroom='', num_washroom=''):
        self.name = name
        self.area = area
        self.num_bedroom = num_bedroom
        self.num_washroom = num_washroom

class HouseProperty(Property):
    def __init__(self, num_warehouse='', garage='', **kw):
        super().__init__(**kw)
        self.num_warehouse = num_warehouse
        self.garage = garage
        Agent.Property_list.append(self)
        # 将创建的房产加入到代理的房产列表中

    def display(self):
        print(self.name)
        print(self.area, self.num_bedroom, self.num_washroom, self.num_warehouse, self.garage)

class ApartmentProperty(Property):
    def __init__(self, balcony='', **kw):
        super().__init__(**kw)
        self.balcony = balcony
        Agent.Property_list.append(self)

    def display(self):
        print(self.name)
        print(self.area, self.num_bedroom, self.num_washroom, self.balcony)

# 建立公寓和房子的子类

house1 = HouseProperty(name="HouseOne", area='100', num_bedroom='1', num_washroom='1', num_warehouse='1', garage='True')
apartment1 = ApartmentProperty(name="ApartmentOne", area='120', num_washroom='1', num_bedroom='2', balcony='True')

print(Agent.Property_list)
agent_one = Agent()
agent_one.display()
print(agent_one.Property_list)

agent_one.create_property("ApartmentTwo")
# 创建一个房产
print(Agent.Property_list)
agent_one = Agent()
agent_one.display()
print(agent_one.Property_list)

上述代码中,对super()函数的使用和函数关键字参数的使用很重要

对于面对对象编程,我们主要是制造接口

猜你喜欢

转载自blog.csdn.net/killeri/article/details/81360132