Skip to main content
 首页 » 编程设计

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

2025年05月04日7落叶无声

我正在尝试以类似图形的方式模拟沿道路行驶的汽车。每个 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 部分:如何从当前对象的方法中调用另一个对象的方法?这两种方法都在同一个类中。

请您参考如下方法:

在我看来,您混淆了class 和object 之间的区别。

类是一段代码,您可以在其中通过指定构成对象的属性和定义对象行为的方法来为对象建模。在本例中,Road 类。

另一方面,对象不过是定义它的类的一个实例。因此它有一个由它的属性值定义的状态。同样,在这种情况下,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])