python truediv,python中__truediv__的运算符重载

本文介绍了在Python中创建分数类并实现加、减、乘、除操作符重载的过程。在尝试实现除法运算时遇到了TypeError,原因是未正确处理__truediv__方法。解决这个问题需要导入`from __future__ import division`来启用浮点除法,或者使用__div__方法。同时,代码展示了如何创建一个分数类,包括求最大公约数(gcd)、获取分子和分母的方法以及比较相等的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值