如何在我的班级中正确地集成add和mul方法?

时间:2016-03-02 14:47:18

标签: python python-2.7

我对课程有疑问。以下是课堂练习的目标:

  

目标:定义一个Python类V2,它代表二维向量并支持以下操作:

     
      
  • 使用两个实数创建一个新向量:v = V2(1.1,2.2)
  •   
  • 将矢量转换为字符串(使用__str__方法)
  •   
  • 访问组件(使用getX和getY方法)
  •   
  • 添加两个V2以获得新的V2(使用添加和__add__方法)
  •   
  • 将V2乘以标量(实数或整数)并返回一个新的V2(使用mul   和__mul__方法)
  •   
     

此处提供了更多信息:

     

步骤3.定义add和mul方法,以便获得以下行为:

>>> a = V2(1.0, 2.0) 
>>> b = V2(2.2, 3.3)
>>> print a.add(b)
V2[3.2, 5.3]
>>> print a.mul(2)
V2[2.0, 4.0]
>>> print a.add(b).mul(-1)
V2[-3.2, -5.3]

以下是我能够编码的内容:

class V2:
    def __init__(self, x, y):
        self.vector = [x, y]
        self.x = x
        self.y = y
    def __str__(self):
        return 'V2[' + str(self.x) + ', ' + str(self.y) + ']'
    def __add__(self, other):
        return 'V2[' + str(self.x + other.x) + ', ' + str(self.y + other.y) + ']'
    def add(self, other):
        return 'V2[' + str(self.x + other.x) + ', ' + str(self.y + other.y) + ']'
    def __mul__(self, y):
        return 'V2[' + str(self.x * y) + ', ' + str(self.y * y) + ']'
    def mul(self, y):
        return 'V2[' + str(self.x * y) + ', ' + str(self.y * y) + ']'
    def getX(self):
        return self.x
    def getY(self):
        return self.y

我的问题是如何让print a.add(b)mul(-1)正确?当我尝试运行时:

>>> p1 = V2(3, 2)
>>> p2 = V2(2, 3)
>>> p1.add(p2).mul(-1)

此错误显示:

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    p1.add(p2).mul(-1)
AttributeError: 'str' object has no attribute 'mul'

我认为我理解了错误,但我无法采用不同的方式来执行addmul方法,而不会弄乱其他方法。

3 个答案:

答案 0 :(得分:2)

您需要创建类的另一个实例而不是字符串:

def __add__(self, v):
    return self.__class__(self.x + v.x, self.y + v.y)

def __mul__(self, n):
    return self.__class__(self.x * n, self.y * n)

然后您可以使用def add(self, v): return self + v。您可以切换这些内容,以便add()是主要方法,__add__调用add

答案 1 :(得分:0)

问题是,在每个方法中,您都返回一个字符串。你不能用字符串做任何算法。目前,你的add方法返回一个字符串然后你调用mul(例如“[v1 3 4]”。mul)。

将add and mult方法更改为返回V2的以下内容。

 def __add__(self, other):
        return V2(self.x + other.x,self.y * other.y)
 def __mul__(self, ascalar):
        return V2(self.x * ascalar, self.y * ascalar)

答案 2 :(得分:0)

在您的方法中,您将返回字符串,而不是V2的新实例。所以它应该是:

class V2:
def __init__(self, x, y):
    self.vector = [x, y]
    self.x = x
    self.y = y
def __str__(self):
    return 'V2[' + str(self.x) + ', ' + str(self.y) + ']'
def __add__(self, other):
    return V2(self.x + other.x, self.y + other.y)
def __mul__(self, c):
    return V2(self.x * c ,self.y * c)
def getX(self):
    return self.x
def getY(self):
    return self.y