Форум сайта python.su
2
Python 3.4.2
Застрял на классах из одной книги
# Нахождение наибольшего общего делителя def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom def __str__(self): return str(self.num) + "/" + str(self.den) def show(self): print(self.num, "/", self.den) def __add__(self, otherfraction): newnum = self.num * otherfraction.den + self.den * otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __eq__(self, other): firstnum = self.num * other.den secondnum = other.num * self.den return firstnum == secondnum def __mul__(self, otherfraction): newnum = self.num * otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __div__(self, otherfraction): newnum = self.num * otherfraction.den newden = self.den * otherfraction.num common = gcd(newnum, newden) return Fraction(newnum // common, newden // common)
TypeError: unsupported operand type(s) for /: 'Fraction' and 'Fraction'
Офлайн
857
>>> class A: ... def __truediv__(self, v): ... print('div', v) ... >>> a = A() >>> a / A() div <__main__.A object at 0xb741de0c> >>>
Офлайн
2
Спасибо, с __truediv__ работает как надо. Да и с __floordiv__ разобрался, IDLE с толку сбивал.
Офлайн