【问题标题】:How to call another Object's Method from the current Object's Method in Python如何在 Python 中从当前对象的方法调用另一个对象的方法
【发布时间】:2013-11-23 20:27:52
【问题描述】:

我正在尝试以类似图形的方式模拟沿道路行驶的汽车。每个 Road 对象都有一个来源和目的地。当一辆车到达路的尽头时,我想让路把它送到下一条路的起点。对于 Road 类,我的代码如下所示:

from collections import deque

class Road:
    length = 10

    def __init__(self, src, dst):
        self.src = src
        self.dst = dst
        self.actualRoad = deque([0]*self.length,10)
        Road.roadCount += 1

    def enterRoad(self, car):
        if self.actualRoad[0] == 0:
            self.actualRoad.appendleft(car)
        else:
            return False

    def iterate(self):
        if self.actualRoad[-1] == 0:
            self.actualRoad.appendleft(0)
        else:
            dst.enterRoad(actualRoad[-1]) #this is where I want to send the car in the last part of the road to the destination road!

    def printRoad(self):
        print self.actualRoad

testRoad = Road(1,2)
testRoad.enterRoad("car1")
testRoad.iterate()

在上面的代码中,问题出在方法iterate()的else部分:如何从当前对象的方法中调用另一个对象的方法?两种方法都在同一个类中。

【问题讨论】:

    标签: python class oop methods


    【解决方案1】:

    在我看来,您混淆了 classobject 之间的区别。

    类是一段代码,您可以在其中通过指定组成对象的属性和定义其行为的方法来对对象进行建模。在这种情况下,Road 类。

    另一方面,对象只不过是定义它的类的一个实例。因此,它具有由其属性值定义的状态。同样,在这种情况下,testRoad 是存储 Road 类对象的变量。

    总之,类是一个抽象模型,而对象是一个具有良好定义状态的具体实例

    那么当你说你想要的时候:

    从当前对象的方法中调用另一个对象的方法

    您真正想要的是在您的类中定义一个方法,该方法允许您从同一类的对象调用另一个方法。

    然后,为此,类方法需要接收您要从中调用的任何方法的对象作为参数:

    def iterate(self, destination_road):
            if self.actualRoad[-1] == 0:
                self.actualRoad.appendleft(0)
            else:
                destination_road.enterRoad(actualRoad[-1])
    

    【讨论】:

      【解决方案2】:

      您必须将另一个Object 作为参数提供给iterate

      def iterate(self, other):
          ...
      

      并从该对象调用方法:

      other.someMethod(...)
      

      【讨论】:

      • 感谢您的回答。我想知道这是否是最好的实施方式,因为我现在意识到每辆到达路尽头的汽车可能会走向不同的道路。在您看来,最好的实现是什么?道路使用链表构建。
      猜你喜欢
      • 2022-12-09
      • 2014-08-17
      • 1970-01-01
      • 2012-10-04
      • 2011-11-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多