Python OOP-能够构建从第一个类对象继承的对象的方法



我是一个真正的新手,所以如果我的标题问题没有很好地定义,我很抱歉。我有一个"世界"类和一个"房子"类。类"World"中有一个方法来构建"House"对象。我不想被迫将"World"对象属性复制到"Houses"对象,因为有很多属性和很多"House"对象。

import numpy as np

class House:

def __init__(self,coordinates):
self.coordinates = coordinates


class World:

def __init__(self,name,x,y): # Please imagine a lot of attributes
self.name = name
self.x = x
self.y = y

def Add_A_Bunch_Of_Houses(self,n):
house_x = np.random.uniform(low=0,high=self.x,size=n)
house_y = np.random.uniform(low=0,high=self.y,size=n)
house_coordinates = zip(house_x,house_y)
self.HOUSES = [House(coords) for coords in house_coordinates]

理想情况下,我希望能够访问"House"对象中的"fantastic_world"属性,如下所示:

fantastic_world = World("narnia",5,5)
fantastic_world.Add_A_Bunch_Of_Houses(10000)
fantastic_world.HOUSES[6678].world_name # does not work obviously

一个快速的答案,因为我不确定你的实际需求是什么,所以如果需要,我可以在与你进一步交流时更新答案。

首先,您可以始终将World实例作为参数传递给新房。那将是最快的解决办法。例如:

class House:
def __init__(self,coordinates,world=None):
self.coordinates = coordinates
self.world = world  # <-- a new field that will hold the reference to world if given

class World:
def __init__(self,name,x,y): # Please imagine a lot of attributes
self.name = name
self.x = x
self.y = y

def Add_A_Bunch_Of_Houses(self,n):
house_x = np.random.uniform(low=0,high=self.x,size=n)
house_y = np.random.uniform(low=0,high=self.y,size=n)
house_coordinates = zip(house_x,house_y)
self.HOUSES = [House(coords,self) for coords in house_coordinates] # <-- mind the self. This is the actual World instance

通过这种方式,您可以使用可选的world参数实例化House,该参数将指向";"父";class(注意,在OOP术语中,它不是父类(。

通过这种方式,您可以通过以下方式访问字段:

fantastic_world = World("narnia",5,5)
fantastic_world.Add_A_Bunch_Of_Houses(10000)
fantastic_world.HOUSES[6678].world # <-- you obviously have access to World instance now. So name would be retrieved by:
fantastic_world.HOUSES[6678].world.name

这是一个快速而肮脏的解决方案。但它并不是真正的OOP。您可以考虑使用数据库和ORM(外键在这里会很好地工作(。

您也可以考虑不同的设计,在那里您继承类或使用Mixin来扩展它们。

希望这能帮助你开始。

最新更新