Python2.7将对象传递给类函数

2024-10-03 06:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python测试我的2D坐标和向量类。以下是定义向量和坐标类的代码:

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))

然后我用下面的语句测试它们:

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)

抛出此错误的位置:

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

我不知道怎么修。inp1我给出的是“0,0”(没有引号),inp2我给出的是“5,5”(同样没有引号)

我认为这可能是一个问题,要么作为函数参数给一个对象,要么作为函数参数给一个坐标,当函数在coordinate类中时?你知道吗

我真的不知道,任何帮助都将不胜感激!你知道吗


Tags: selfcoordinatedefintresolvecoordmagnitudevector1
2条回答

resolve的第一个参数应该是self。你知道吗

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

所有方法(像函数但在类中)都接受第一个参数self,如__init__()方法所示。你知道吗

def resolve(endCoord):

应该是

def resolve(self, endCoord):

参见relevant docs。你知道吗

相关问题 更多 >