The 'int' object cannot be called

I am trying to define a simple class Fraction

And I get this error:

python fraction.py 
Traceback (most recent call last):
File "fraction.py", line 20, in <module>
   f.numerator(2)
TypeError: 'int' object is not callable

The following code:

class Fraction(object):
    def __init__( self,  n=0, d=0 ):
       self.numerator = n
       self.denominator = d
    def get_numerator(self):
        return self.numerator
    def get_denominator(self):
         return self.denominator

    def numerator(self, n):
         self.numerator = n
    def denominator( self, d ):
         self.denominator = d

    def prints( self ):
          print "%d/%d" %(self.numerator, self.denominator)

if __name__ == "__main__":
    f = Fraction()
    f.numerator(2)
    f.denominator(5)
    f.prints()

I thought it was because I had numerator(self)and numerator(self, n), but now I know that Python has no method overload (function overload), so I renamed to get_numerator, but that is not a problem.

What could it be?

+3
source share
3 answers

You use numeratorboth the name of the method ( def numerator(...)) and the name of the member variable ( self.numerator = n). Use set_numeratorboth set_denominatorfor the method name and it will work.

By the way, Python 2.6 has a built-in class.
+18
source

numerator, -, . self.numerator = n, , , f.numerator(2), -, int, Python . x = 2; x(4) - .

setter set_numerator set_denominator, .

+9
  • numerator , . , , . (Python , .)

    , , f.numerator(2), f.numerator , 0, 0, .

  • , stdlib fractions: http://docs.python.org/library/fractions.html p >

    • Python 2.6. , Python, , , sympy Rational.
  • denominator , , 1. ( Fraction(5) , - undefined, .)

  • prints __str__ .

  • . Python - .

    • Java, getter setter, . , - , ( ), API. Python , API , .
  • Do no harm to inheritance numbers.Rational(Python 2.6 and later), which allows your class to automatically do several things. You will need to do everything you need, but then it will automatically do a lot more work. Check out http://docs.python.org/library/numbers.html to learn more.


Spoiler warning:

class Fraction(object):
    """Don't forget the docstring....."""

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

    def __str__(self):
        return "%d / %d" % (self.numerator, self.denominator)

    # I probably want to implement a lot of arithmetic and stuff!

if __name__ == "__main__":
    f = Fraction(2, 5)
    # If I wanted to change the numerator or denominator at this point, 
    # I'd just do `f.numerator = 4` or whatever.
    print f
+7
source

Source: https://habr.com/ru/post/1742541/


All Articles