class Field(object):
def __init__(self):
self.drunks = {}
def addDrunk(self, drunk, loc):
if drunk in self.drunks:
raise ValueError('Duplicate drunk')
else:
self.drunks[drunk] = loc
def moveDrunk(self, drunk):
if not drunk in self.drunks:
raise ValueError('Drunk not in field')
xDist, yDist = drunk.takeStep()
currentLocation = self.drunks[drunk]
#use move method of Location to get new location
self.drunks[drunk] = currentLocation.move(xDist, yDist)
def getLoc(self, drunk):
if not drunk in self.drunks:
raise ValueError('Drunk not in field')
return self.drunks[drunk]
import random
def walk(f, d, numSteps):
start = f.getLoc(d)
for s in range(numSteps):
f.moveDrunk(d)
return(start.distFrom(f.getLoc(d)))
我正在学习 python。我看到了这段代码,我不明白为什么 walk 函数可以使用 moveDrunk() 方法?不应该因为 moveDrunk() 来自 Field 类而引发错误?