python - 从实例而不是类继承 [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 复制出属性,但这也有与上面相同的问题,而且我没有以这种方式获得方法。
我想要某种传递建筑物特定实例的方法,以便房间继承其特定属性和方法。
欢迎任何反馈、建议、批评以及完全不同的方式!先感谢您!
解决方案
A Room
is 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)
推荐阅读
- windows - 分支开关上的文件夹大小写不变
- php - 在 Laravel 中使用 Redis 缓存图像?
- javascript - 文件不会在 Notepad++ 中另存为 JavaScript 扩展
- node.js - 登录后无法获取 jwt 令牌
- mongodb - MongoDB oplog 包含许多 Noop
- postgresql - postgres 10 对等身份验证失败
- c# - 在反序列化 JSON 文件时不使用完整路径
- matlab - 如何在 MATLAB 中实现人口普查变换
- f# - 如何在 \n 处反转字符串列表中的每个字符串?
- amazon-web-services - 启用 CDN 到 S3 存储桶而不授予 AWS 中的公共访问权限