2015-04-28 46 views
-2

我想在python中測試我的2D座標和向量類。這裏是其中載體和座標類別被定義的代碼:Python 2.7將對象傳遞給類函數

inp1 = raw_input("Please enter the first coordinate: ") 
inp2 = raw_input("Please enter the second coordinate: ") 
coord1 = coord(int(inp1[0]), int(inp1[2])) 
coord2 = coord(int(inp2[0]), int(inp2[2])) 
vector1 = coord1.resolve(coord2) 
print "Vector magnitude is "+str(vector1.magnitude) 

我得到與線路中的問題::

vector1 = coord1.resolve(coord2) 

class coord(object): 
    def __init__(self,x,y): 
     self.x = x 
     self.y = y 
    def resolve(endCoord): 
     return vector((self.x-endCoord.x),(self.y-endCoord.y)) 

class vector(object): 
    def __init__(self, xTrans, yTrans): 
     self.xTrans = xTrans 
     self.yTrans = yTrans 
     self.magnitude = sqrt((self.xTrans**2)+(self.yTrans**2)) 

我然後用下面的語句測試這些

它會拋出此錯誤:

exceptions.TypeError: resolve() takes exactly 1 argument (2 given) 

我不知道如何解決它。我給出的inp1是「0,0」(不帶引號),對於inp2我給出了「5,5」(再次沒有引號)

我認爲這可能是一個問題,或者將對象作爲函數參數或事實我給一個座標作爲函數參數,當函數在座標類內?

我真的不知道,任何幫助將不勝感激!

回答

3

resolve的第一個參數應該是self

class coord(object): 
    ... 
    def resolve(self, endCoord): 
     return vector((self.x-endCoord.x),(self.y-endCoord.y)) 
1

所有的方法(如功能,但在班)接受的第一個參數爲self,如圖您__init__()方法。

def resolve(endCoord): 

應該

def resolve(self, endCoord): 

relevant docs