2016-08-07 2 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 

Iはベクトル期待していた(0.4を、-5)の代わりにベクトル(0、-5)、どのようにこれを達成することができますか?

いくつかの有用なリンクは以下のとおりです。
https://docs.python.org/2/library/operator.html
http://www.tutorialspoint.com/python/python_classes_objects.htm

+1

あなたがそれらの将来のインポートを必要としない場合 – 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) 
関連する問題