我已经制作了一个类向量,但是当我想要划分Vector / 0时它没有正确划分,它不会抛出错误:
class Vector(tuple):
'''"Class to calculate the usual operations with vectors in bi and
tridimensional coordinates. Too with n-dimmensinal.'''
# __slots__=('V') #It's not possible because V is a variable list of param.
def __new__(cls, *V):
'''The new method, we initialize the coordinates of a vector.
You can initialize a vector for example: V = Vector() or
V = Vector(a,b) or V = Vector(v1, v2, ..., vn)'''
if not V:
V = (0, 0)
elif len(V) == 1:
raise ValueError('A vector must have at least 2 coordinates.')
return tuple.__new__(cls, V)
def __mul__(self, V):
'''The operator mult overloaded. You can multipy 2 vectors coordinate
by coordinate.'''
if type(V) == type(self):
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions')
else:
multiplied = tuple(a * b for a, b in zip(self, V))
elif isinstance(V, type(1)) or isinstance(V, type(1.0)):
multiplied = tuple(a * V for a in self)
return Vector(*multiplied)
__rmul__ = __mul__
def make_one(self, long):
one = tuple(1 for a in range(0, long))
return Vector(*one)
def __truediv__(self, V):
if type(V) == type(self):
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions.')
if 0 in V:
raise ZeroDivisionError('Division by 0.')
divided = tuple(a / b for a, b in zip(self, V))
return Vector(*divided)
elif isinstance(V, int) or isinstance(V, float):
if V == 0:
return self * V * Vector().make_one(len(self))
#raise ZeroDivisionError('Division by 0.')
return self * (1 / V) * Vector().make_one(len(self))
__rtruediv__ = __truediv__
测试代码:
from Vector import Vector
def main():
V1 = Vector(3, 2, -1, 5)
print(0 / V1)
print(V1 / 0)
if __name__ == '__main__':
main()
控制台输出
(0,0,0,0) (0,0,0,0)
第一个输出是正确的,但第二个输出是错误的,正确的方法是ErrorDivision 0。
答案 0 :(得分:0)
好的,感谢@ user2357112,正确的代码是:
def __truediv__(self, V):
if type(V) == type(self):
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions.')
if 0 in V:
raise ZeroDivisionError('Division by 0.')
divided = tuple(a / b for a, b in zip(self, V))
return Vector(*divided)
elif isinstance(V, int) or isinstance(V, float):
if V == 0:
raise ZeroDivisionError('Division by 0.')
return self * (1 / V) * Vector().make_one(len(self))
#__rtruediv__ = __truediv__
def __rtruediv__(self, V):
if isinstance(V, int) or isinstance(V, float):
if V == 0:
return self * V * Vector().make_one(len(self))
return self * (1 / V) * Vector().make_one(len(self))