在Python中如何从当前对象的方法调用另一个对象的方法

2024-10-04 07:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用图形的方式模拟汽车在道路上行驶。每个道路对象都有一个源和目标。当一辆车到达路的尽头时,我希望这条路把它送到下一条路的起点。对于道路类,我的代码如下所示:

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部分:如何从当前对象的方法调用另一个对象的方法?两个方法在同一个类中。在


Tags: the对象方法selfsrcdefcarelse
2条回答

必须将另一个Object作为iterate的参数:

def iterate(self, other):
    ...

从该对象调用方法:

^{pr2}$

在我看来,你混淆了object之间的区别。在

类是通过指定组成对象的属性和定义对象行为的方法来对对象建模的代码段。在这种情况下,道路类。在

另一方面,对象只是定义它的类的一个实例。因此,它有一个由it属性值定义的状态。同样,在本例中,testRoad是存储Road类对象的变量。在

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

所以当你说你想要:

call another Object's method from the current Object's Method

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

然后,要执行此操作,类方法需要以参数形式接收要从中调用任何要调用的方法的对象:

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

相关问题 更多 >