1

I started to learn Python 2 weeks ago, and I was doing an exercise about class (which consists of creating my own "Fraction" class) when I got the error in the title. Why ? And how to solve it ? Sorry, i'm not the type of person who often ask for help, but now I really don't know how to solve it. It seems that the error occurs only in "str" method.

Here you have my code(idk if this will appear properly..):

from math import gcd

class Fraction :

    def __init__(self,a,b):
        self.num = a
        self.den = b

    def __str__(self):
        return str(self.num)+" / "+str(self.den)

    def reduire(self):
        return self.num//gcd(self.num,self.den) , self.den//gcd(self.num,self.den)

frac = Fraction(30,40)
print(Fraction.__str__(Fraction.reduire(frac)))
3
  • 4
    reduire returns a tuple, and then you try to get the num field, and tuples don't have named fields. You probably want reduire to return a Fraction. Commented Aug 12, 2022 at 18:30
  • As a side, do you know Python 2 is not receiving updates since 2020? If you are learning just for the sake of knowing python or learning to program, you may want to consider using Python 3. Commented Aug 12, 2022 at 18:37
  • Suggestions to slow down the learning speed - try to get the basics covered/familiar then OOP Commented Aug 12, 2022 at 18:37

1 Answer 1

1

First of all, you call reduire as if it is a class/static method, but it is an instance method, so it is more natural to call it as frac.reduire()

The error comes from your call of __str__ (which again you call as if it is a class/static method) and you pass it the value that reduire returns (a tuple) instead of the frac instance. The __str__ function expects the fraq instance (self) as argument. This can be done better with str(fraq), in a separate statement.

But as your goal is to print, this call of str (and __str__) can actually be omitted. print already takes care of this. So just do:

frac.reduire()
print(frac)  # this implicitly calls `__str__`
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.