2016-08-07 5 views
2

내가 이런 코드가 있습니다python3의 클래스에 대해 truediv를 사용하는 방법은 무엇입니까?

# 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

만약 당신이 미래의 가져올 필요가 없습니다 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) 
관련 문제