![](/img/trans.png)
[英]How to access attribute of object from another object's method, which is one of attributes in Python?
[英]How to call another Object's Method from the current Object's Method in Python
我正在尝试以图形方式模拟沿着道路行驶的汽车。 每个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()的其他部分:我如何从当前对象的方法中调用另一个对象的方法? 两种方法都在同一类中。
在我看来,您正在混淆类和对象之间的区别。
类是一段代码,您可以在其中通过指定组成对象的属性和定义其行为的方法来对对象进行建模。 在这种情况下, 道类。
另一方面,对象不过是定义它的类的实例而已。 因此,它具有一个由其属性值定义的状态。 同样,在这种情况下, testRoad是存储Road类的对象的变量。
一言以蔽之,虽然类是一个抽象模型,但对象是具有明确定义状态的具体实例 。
因此,当您说要:
从当前对象的方法调用另一个对象的方法
您真正想要的是在类中定义一个方法,该方法允许您从同一类的对象调用另一个方法。
然后,为此,类方法需要将要从中调用任何方法的对象作为参数接收:
def iterate(self, destination_road):
if self.actualRoad[-1] == 0:
self.actualRoad.appendleft(0)
else:
destination_road.enterRoad(actualRoad[-1])
您必须将另一个Object
作为参数进行iterate
:
def iterate(self, other):
...
并从该对象调用方法:
other.someMethod(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.