【问题标题】:Python 2.7 passing an object to a class functionPython 2.7 将对象传递给类函数
【发布时间】:2015-07-07 03:50:31
【问题描述】:

我正在尝试在 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”(同样不带引号)

我认为当函数在坐标类中时,将对象作为函数参数或我将坐标作为函数参数的事实可能是一个问题?

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

【问题讨论】:

    标签: python python-2.7 object parameter-passing


    【解决方案1】:

    resolve 的第一个参数应该是 self

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

    【讨论】:

      【解决方案2】:

      所有方法(如函数但在类中)都接受第一个参数为self,如您的__init__() 方法中所示。

      def resolve(endCoord):
      

      应该是

      def resolve(self, endCoord):
      

      请参阅relevant docs

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-18
        • 2012-05-01
        • 2015-02-01
        • 2014-06-04
        • 1970-01-01
        • 2013-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多