我想启动子类的多个实例,每个子类从类的特定实例而不是通用类中获取属性。
例如,如果我有建筑物和房间,则每个房间都需要属于建筑物的特定实例,并采用其属性和方法。
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
Run Code Online (Sandbox Code Playgroud)
假设我有三栋建筑:“北”、“南”和“西”。
每栋楼都有自己的房间。
仅看北楼,它有“N1”、“N2”、“N3”、“N4”房间。
在我的代码中,我将首先遍历并启动三座建筑物,然后我将启动房间,以某种方式将它们链接回其相应的建筑物。
这允许我使用 Directions 方法,该方法利用其父类实例的属性位置,该属性对于该建筑物来说是唯一的,而不是一般值。它还需要能够使用父类 Evacuate_Building 中的方法。
每次我使用 super(buildingName, location) 或 Building.__ init__(self,buildingName, location) 在更标准的设置中启动一个房间时,我可以通过传递位置数据来解决这个问题,但这意味着我必须编写位置每个房间,如果我在建筑物中添加或更改某些内容,如果添加了其他属性,我需要更改每个房间的初始化和初始化代码。 …