2016-08-07 49 views
2

我有這樣的代碼:如何使用truediv在python3中的類?

# 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),我怎麼能做到這一點?

一些有用的鏈接如下:
https://docs.python.org/2/library/operator.html
http://www.tutorialspoint.com/python/python_classes_objects.htm

+1

如果您在python 3中,則不需要那些將來導入 – Copperfield

回答

4

值是正確的,但印錯了,因爲你鑄造結果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)