Question

I get the error:

TypeError: 'int' object is not callable

when I try to do something like this:

first = Rational()
print(first.numerator())

below is my code:

class Rational:

def __init__(self, numerator=0, denominator=1):
    self.numerator = numerator
    self.denominator = denominator

def numerator(self):
    return self.numerator

def denominator(self):
    return self.denominator

def __str__(self):     
    return str(self.numerator) + "/" + str(self.denominator)

It appears that python thinks that numerator is of type int, but I thought I made it as an attribute of the Rational Class. I'm terribly confused.

Thanks for any clarification!

Was it helpful?

Solution

You have too many numerators in your code... ;-) You have one attribute called numerator on the first line of the __init__ method and another one as a method defined by def numerator(self). There are different possibilities depending on what you need:

  1. Delete the method and use always first.numerator.
  2. Rename the attribute so that they have no conflicts.
  3. Use a @property clause, but I don't think why you would do that in this case, because there is nothing to calculate or modify to the attribute,

OTHER TIPS

You're looking for:

class Rational:

    def __init__(self, numerator=0, denominator=1):
        self._numerator = numerator
        self.denominator = denominator

    @property
    def numerator(self):
        return self._numerator

Then your calling code would look like:

first = Rational()
print(first.numerator)

What's happening in your code is that Rational.numerator is being bound to the method you're defining at module import time, as per normal. However, your __init__ method is explicitly saying "create an instance attribute named denominator bound to this int object". That new instance attribute is resolved before the class attribute with the same name, so any references to instance.denominator will resolve to that instance attribute.

My suggested replacement, if you truly want to implement a getter (which isn't particularly Pythonic; you already have a way to access instance.denominator built-in!), is to store it in a privately-named variable and create a publicly-named property method that loads its value and returns it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top