python truediv_python中__truediv__的运算符重载

I am trying to implement overloading for division operator in python.

class Fraction:

def __init__(self,top,bottom):

def gcd(m, n):

while m % n != 0:

old_m = m

old_n = n

m = old_n

n = old_m % old_n

return n

common = gcd(top,bottom)

self.num = top/common

self.den = bottom/common

def __str__ (self):

return str(self.num) + "/" + str(self.den)

def get_num(self):

return self.num

def get_den(self):

return self.den

def __add__(self, other_fraction):

new_num = self.num * other_fraction.den + self.den * other_fraction.num

new_den = self.den * other_fraction.den

return Fraction(new_num, new_den)

def __sub__(self, other_fraction):

new_num = self.num * other_fraction.den - self.den * other_fraction.num

new_den = self.den * other_fraction.den

return Fraction(new_num, new_den)

def __mul__ (self, other_fraction):

new_num = self.num * other_fraction.num

new_den = self.den * other_fraction.den

return Fraction(new_num, new_den)

def __truediv__(self, other_fraction):

new_num = self.num * other_fraction.den

new_den = self.den * other_fraction.num

return Fraction(new_num, new_den)

def __eq__(self, other):

first_num = self.num * other.den

second_num = other.num * self.den

return first_num == second_num

a = Fraction(10,20)

b = Fraction(30,20)

print a

print "numerator is",a.get_num()

print "denominator is",a.get_den()

print "equality is",(a==b)

print "sum is",(a+b)

print "difference is",(a-b)

print "product is",(a*b)

print "division is",(a/b)

But the __truediv__ is giving error as

TypeError: unsupported operand type(s) for /: 'instance' and

'instance'

Pls help whats wrong with the code?

解决方案

The object.__truediv__() special method is only used with the / operator and then only if you have switched the Python compiler to use true division with:

from __future__ import division

If you did not use that import, the / operator calls the object.__div__() special method if present.

The // operator on the other hand calls the object.__floordiv__() special method, which you did not implement.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值