我有一个Drone类和一个Building类。 Building类有两个名为x0
和y0
的属性。我想用这两个变量' Drone类中的值,但我还没有能够解决这个问题。
以下是建筑代码:
class Building(Agent):
def __init__(self, pos, x0, y0, model, request=False):
# Buildings won't have requests initially (set to false)
super().__init__(pos, model)
self.pos = pos
self.x0 = x0
self.y0 = y0
self.model = model
self.request = request
和无人机:
class Drone(Agent):
grid = None
x = None
y = None
moore = True
def __init__(self, name, model, x, y, speed, battery, heading, moore=True):
super().__init__(name, model)
self.name = name
self.model = model
self.x = x
self.y = y
self.speed = speed
self.battery = battery
self.heading = heading
self.moore = moore
def step(self):
if self.name == 1:
if self.x < Building.x0:
self.x += 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
elif self.x > Building.x0:
self.x -= 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
if self.y < Building.y0:
self.y += 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
elif self.y > Building.y0:
self.y -= 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
答案 0 :(得分:0)
我不相信你理解面向对象编程的哲学。如果它们都需要相同的信息(x0,y0),那么它们应该是相同的对象,或者应该在它们继承的对象上建立x0和y0,以便子类已经拥有数据。例如。
agent.x0 = x0
agent.y0 = y0
这样建筑物和无人机都有关于创造的信息。但实际上,应该考虑重构。
答案 1 :(得分:-1)
class Building:
def __init__(self, x0, y0):
self.x0 = x0
self.y0 = y0
class Drone:
x = None
y = None
def __init__(self, x, y):
self.x = x
self.y = y
def step(self, building):
if self.x < building.x0:
etc
您的Building类没有类变量x0,y0。 Building类的实例可以。因此,您的Building.x0代码没有意义。
building1 = Building(x_bldg, y_bldg)
drone1 = Drone(x_drn, y_drn)
drone1.step(building1)