2013-02-19 184 views
0
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.I看到了這段代碼,我不明白爲什麼walk函數可以使用moveDrunk()方法嗎?不應該因爲moveDrunk()來自Field類而引發錯誤?python方法繼承

回答

0

您傳遞Field類(f)的實例作爲參數:

def walk(f, d, numSteps): 
     ^
+0

是不是˚F只是一個說法?爲什麼f是Field的一種? – lucas 2013-02-19 06:08:12

+0

@lucas:這就是它應該是的樣子。你應該傳遞一個Field的實例作爲第一個參數。我不確定你在問什麼。 – Blender 2013-02-19 06:11:32

+0

因此,如果我不傳遞Field的實例作爲第一個參數會引發錯誤? – lucas 2013-02-19 06:15:15