欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用面向对象的思想实现一个有理数以及有理数的加减乘除运算——Python版本

程序员文章站 2022-06-25 20:17:07
...
class Rational(object):
  def __init__(self,a,b=1):
    if(b ==0 ):#对于分母为0的情况直接举异常
      raise Exception("Denominator must not be 0!")
    else:
      g = self.gcd(abs(a), abs(b))#求分子分母的最大公约数然后进行约分
      self.a = a/g
      self.b = b/g

  def gcd(self,a,b):#求最大公约数
    if(b==0):return a
    else:return self.gcd(b,a%b)
#以下为运算符重载
  def __add__(self, another):
    try:
      return Rational(self.a*another.b +another.a*self.b,self.b*another.b)
    except TypeError:
      return NotImplemented

  def __mul__(self, another):
    try:
      return Rational(self.a*another.a,self.b*another.b)
    except TypeError:
      return NotImplemented

  def __sub__(self, another):
    try:
      return Rational(self.a * another.b - self.b * another.a, self.b * another.b)
    except TypeError:
      return NotImplemented

  def __div__(self, another):
    try:
      return Rational(self.a * another.b, self.b * another.a)
    except TypeError:
      return NotImplemented

  def __str__(self):
    return '%s/%s' % (self.a, self.b) if self.b != 1 else str(self.a)

# Below are tests:

a = Rational(3,6)
b = Rational(4,5)

print a,b

print a+b
print a*b
print b-a
print b/a

a = Rational(3,7)
b = Rational(4)
print a,b

print a+b
print a*b
print b-a
print b/a

a = Rational(3)
b = Rational(4,7)
print a,b

print a+b
print a*b
print b-a
print b/a

注意

在运算符重载的时候Python2和Python3有细微的不同,如果没有实际经验会报以下错误

TypeError: unsupported operand type(s) for /: ‘Rational’ and ‘Rational’

问题主要出在重载除法运算符的时候2和3有以下差异:

Python3 uses special division names: __truediv__ and __floordiv__ for the / and // operators, respectively.
python2 uses __div__