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.x, other.y, other.z

次に、__mul__メソッドで:

if type(scalar)!=int or float:

次のように変更する必要があります:

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

于 2012-12-30T17:11:56.570 に答える