NB Noob警报......!
我试图在Python类方法中使用递归,但结果有限.
我正在尝试构建一个具有非常基本属性的汽车类:id,单道道路中的位置(由整数表示)和速度.我拥有的其中一个功能是用来返回这个车身ID在前面 - 即如果我们有课程:
class Car:
def __init__(self, position, id, velocity):
self.position = position
self.id = id
self.velocity = velocity
Run Code Online (Sandbox Code Playgroud)
现在,我想出了以下类方法(代码下面的其他详细信息):
def findSuccessorCar(self, cars):
successorCar = ""
smallestGapFound = 20000000
for car in cars:
if car.id == self.id: continue
currentGap = self.calculateGap(car)
if (currentGap > -1) and (currentGap < smallestGapFound):
smallestGapFound = currentGap
successorCar = car
if successorCar == "":
return 1 # calling code checks for 1 as an error code
else:
return successorCar
Run Code Online (Sandbox Code Playgroud)
计划是创建汽车对象,然后将它们存储在列表中.每次调用findSuccessorMethod时,都会将此全局汽车列表传递给它,例如
c1 = …Run Code Online (Sandbox Code Playgroud) python ×1