首页 > 解决方案 > 从实例而不是类继承 [Python 3]

问题描述

我想启动一个子类的多个实例,每个实例都从一个类的特定实例而不是通用类中获取它们的属性。

例如,如果我有建筑物和房间,每个房间都需要属于建筑物的特定实例,并采用其属性和方法。

class Building:
     def __init__(self, buildingName, location):
        self.buildingName = buildingName
        self.location = location
        # lots more intersting stuff

    def Evacuate_Building(self):
        # do some stuff
        pass

class Room(Building):
     def __init__(self, roomName, roomType):
        self.roomName = roomName
        self.roomType = roomType
        # lots more intersting stuff

    def Directions(self, Current_Location):
        '''do some stuff involving this.roomName and this.location which comes from the specific instance of the class'''
        pass

假设我有三座建筑物:“北”、“南”和“西”。

每栋楼都有自己的房间。

只看北楼,它有房间'N1','N2','N3','N4'。

在我的代码中,我会先浏览并启动三个建筑物,然后我会启动房间,一些如何将它们链接回其对应的建筑物。

这允许我使用 Directions 方法,该方法利用其父类实例中的属性位置,该属性是该建筑物所独有的,而不是一般值。它还需要能够使用父类 Evacuate_Building 中的方法。

我可以通过每次使用 super(buildingName, location) 或 Building.__ init__(self, buildingName, location) 在更标准的设置中启动房间时传递位置数据来解决这个问题,但这意味着我必须为每个房间,如果我在建筑物中添加或更改某些内容,如果添加了其他属性,我需要更改每个房间的初始化和初始化代码。

我也可以通过将 Building 的实例作为参数传递给 init 然后将 this.location = building.location 复制出属性,但这也有与上面相同的问题,而且我没有以这种方式获得方法。

我想要某种传递建筑物特定实例的方法,以便房间继承其特定属性和方法。

欢迎任何反馈、建议、批评以及完全不同的方式!先感谢您!

标签: pythonclassoopinheritance

解决方案


A Roomis not a Building==>Room不应该是 的子类Building
ABuilding有很多Room==> 使用组合。

一种可能的方法是让每个Building人都有一个集合Room

class Building:
    def __init__(self, name, location):
        self.name = name
        self.location = location
        self.rooms = []            # or a set as in @Abamert's reply
                                   # or dict if you want to address it by floor and number, maybe?
    def add_room(self, room):
        self.rooms.append(room)

class Room:
    def __init__(self, name, model):
        self.name = roomName
        self.model = model

你也可以,也许,让房间引用它们所在的建筑物;此引用可能是在向建筑物添加房间时分配的属性:

class Building:
    ...
    def add_room(self, room):
        room.bldg = self
        self.rooms.append(room)

推荐阅读