A
A
Alexander2020-04-18 16:44:55
Python
Alexander, 2020-04-18 16:44:55

Fraction class: how to add integer operations?

Good afternoon! I wrote a code to work with fractions:

spoiler
class Fraction:
    
    def __init__(self, a, b):
        self.a = a
        self.b = b
        
    def __str__(self):
        return '{}/{}'.format(self.a, self.b)
    
    def __add__(self, other):
        return Fraction(self.a + other.a, self.b + other.b)
    
    def __sub__(self, other):
        return Fraction(self.a - other.a, self.b - other.b)
    
    def __mul__(self, other):
        return Fraction(self.a * other.a, self.b * other.b)

Calls like Fraction(10, 1) + Fraction(2, 20) work just fine. But the task is still like this:

It is assumed that the operation of addition / subtraction / multiplication can be carried out both only between fractions, and between a fraction and an integer.

That is, calling Fraction(1, 2) + 3 should work. And I throw out AttributeError: 'int' object has no attribute 'a' , because the necessary piece of code is missing. I don't understand what should be in there. Help me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-04-18
@yolga

def __add__(self, other):
        if isinstance(other, int):
            return результат сложения дроби и целого числа
        return Fraction(self.a + other.a, self.b + other.b)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question