0

我有一个类名“vector”,我需要实现一些方法。我在代码中内置了“doctest.testmod()”。我写了我需要的所有方法(除了 str 和 repr),但我不明白为什么我会遇到所有这些失败。如果anypne可以提供帮助,我会很高兴。tnx。

from math import sqrt

class Vector:

    def __init__(self, x = 0, y = 0, z = 0):        
        self.x=x
        self.y=y
        self.z=z

    def to_tuple(self):
        '''
        >>> Vector(1,0,0).to_tuple()
        (1, 0, 0)
        '''
        return (self.x,self.y,self.z)

    def __str__(self):
        '''
        __str__
        >>> str(Vector(1.0, 0.0, 1.0))
        '(1.0, 0.0, 1.0)'
        '''
        return str(self.to_tuple())

    def __repr__(self):
        return str(self)

    def __eq__(self, other):
        '''
        >>> Vector(3,6,10.) == Vector(3.,6.,10)
        True
        >>> Vector(1,0.,-1.) == Vector(1.,0.,1)
        False
        '''
        if self.x==other[0] and self.y==other[1] and self.z==other[2]:
            return True
        else:
            return False

    def __add__(self, other):      
        '''
        >>> Vector(1,2,3) + Vector(0.5,3,-1)
        (1.5, 5, 2)
        '''  
        return (self.x+other[0],self.y+other[1],self.z+other[2])

    def __neg__(self):
        '''
        >>> -Vector(1,8,-4.3)
        (-1, -8, 4.3)
        '''
        return (self.x*-1,self.y*-1,self.z*-1)

    def __sub__(self, other):
        '''
        >>> Vector(1,2,3) - Vector(0.5,3,-1)
        (0.5, -1, 4)
        '''
        self.__add__(other.__neg__)

    def __mul__(self, scalar):
        '''
        >>> Vector(1,5,3) * 2
        (2, 10, 6)
        >>> Vector(1,5,3) * (-0.5)
        (-0.5, -2.5, -1.5)
        '''
        if type(scalar)!=int or float:
            raise TypeError("Vector multiplication only defined for scalar")
        else:
            return (scalar*self.x,scalar*self.y,scalar*self.z)
    def inner(self, other):  
        '''
        >>> Vector(1,2,3).inner(Vector(-1,5,3))
        18
        '''     
        return (self.x*other[0]+self.y*other[1]+self.z*other[2])

    def norm(self):
        '''
        >>> Vector(0,3,4).norm()
        5.0
        '''
        return sqrt(self.inner(self))

import doctest


doctest.testmod()

输出:

6 items had failures:
   1 of   1 in __main__.Vector.__add__
   2 of   2 in __main__.Vector.__eq__
   2 of   2 in __main__.Vector.__mul__
   1 of   1 in __main__.Vector.__sub__
   1 of   1 in __main__.Vector.inner
   1 of   1 in __main__.Vector.norm
***Test Failed*** 8 failures.
4

1 回答 1

3

__add__,__eq____inner__方法中,您可以通过索引访问 other 的字段,但您应该像访问它们一样other.x, other.y, other.z

然后,在__mul__方法中:

if type(scalar)!=int or float:

应更改为:

if not isinstance(scalar, (int, float)):

于 2012-12-30T17:11:56.570 回答