如何在另一个类中使用一个类的变量?

问题描述 投票:0回答:2

我有无人机课程和建筑课程。 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)
python
2个回答
0
投票

我不相信你理解面向对象编程的哲学。如果它们都需要相同的信息(x0,y0),那么它们应该是同一个对象,或者x0和y0应该建立在它们继承的对象上,以便子类已经拥有数据。例如。

agent.x0 = x0
 agent.y0 = y0

以便建筑物和无人机都拥有有关创建的信息。但实际上,应该考虑重构。


-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)
© www.soinside.com 2019 - 2024. All rights reserved.