Python 3.x 如何将truediv用于python3中的类?
我有这样一个代码:Python 3.x 如何将truediv用于python3中的类?,python-3.x,division,Python 3.x,Division,我有这样一个代码: # Imports from __future__ import print_function from __future__ import division from operator import add,sub,mul,truediv class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vec
# Imports
from __future__ import print_function
from __future__ import division
from operator import add,sub,mul,truediv
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
def __sub__(self,other):
return Vector(self.a - other.a, self.b - other.b)
def __mul__(self,other):
return Vector(self.a * other.a, self.b * other.b)
# __div__ does not work when __future__.division is used
def __truediv__(self, other):
return Vector(self.a / other.a, self.b / other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
print (v1 - v2)
print (v1 * v2)
print (v1 / v2) # Vector(0,-5)
print(2/5) # 0.4
print(2//5) # 0
我期待的是向量(0.4,-5)而不是向量(0,-5),我如何才能做到这一点
一些有用的链接是:该值是正确的,但打印错误,因为您正在将结果强制转换到
int
此处:
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
# ---^---
您可以将其更改为:
def __str__(self):
return 'Vector ({0}, {1})'.format(self.a, self.b)
这将打印:
Vector (0.4, -5.0)
如果您使用的是Python3,那么以后就不需要这些导入