Ошибка int object is not callable питон

I’m trying to define a simply Fraction class

And I’m getting 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 code follows:

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 Python doesn’t have method overloading ( function overloading ) so I renamed to get_numerator but that’s not the problems.

What could it be?

SilentGhost's user avatar

SilentGhost

306k66 gold badges305 silver badges292 bronze badges

asked Apr 23, 2010 at 22:29

OscarRyz's user avatar

OscarRyzOscarRyz

196k112 gold badges385 silver badges569 bronze badges

1

You’re using numerator as both a method name (def numerator(...)) and member variable name (self.numerator = n). Use set_numerator and set_denominator for the method names and it will work.

By the way, Python 2.6 has a built-in fraction class.

answered Apr 23, 2010 at 22:31

interjay's user avatar

4

You can’t overload the name numerator to refer to both the member variable and the method. When you set self.numerator = n, you’re overwriting the reference to the method, and so when you call f.numerator(2), it’s trying to do a method call on the member variable, which is an int, and Python doesn’t let you do that. It’s like saying x = 2; x(4) — it just doesn’t make any sense.

You should rename the setter methods to set_numerator and set_denominator to remove this naming conflict.

answered Apr 23, 2010 at 22:32

Adam Rosenfield's user avatar

Adam RosenfieldAdam Rosenfield

389k97 gold badges512 silver badges586 bronze badges

  • You are using numerator as both a method name and a name for an instance attribute. Since methods are stored on the class, when you lookup that attribute you get the number, not the method. (Python will look up attributes on the instance before looking at the class.)

    That is to say that on the line where you say f.numerator(2), it looks up f.numerator and finds that it is 0, then tries to call that 0, which obviously shouldn’t work.

  • If you have any practical purpose for this code, you can use the stdlib fractions module: http://docs.python.org/library/fractions.html

    • This is new in Python 2.6. If I needed to represent fractions but was using an earlier version of Python, I’d probably use sympy’s Rational type.
  • A more practical default value for denominator is probably 1. (That way Fraction(5) would be five, not some undefined operation tending towards infinity.)

  • Rather than a prints method, it would be more typical to define __str__ and just print your object.

  • Your methods are just getting and setting an attribute. In Python, we generally do not use getters and setters—we just let users set our attributes.

    • You’re coming from a Java background, where one of the basic rules is always to use getter and setter methods rather than let users access attributes. The rationale for this rule is that if, at some future date, you needed to do more than just get and set (you needed to process the data), it would require an API change. Since in Python we have properties, we would not need an API change in that instance so we can safely avoid the boilerplate and cruft of setters and getters.
  • It wouldn’t hurt to inherit numbers.Rational (Python 2.6 and up), which lets your class automatically do several things numbers are expected to. You will have to implement everything it needs you to, but then it will automatically make a lot more work. Check out Check out http://docs.python.org/library/numbers.html to learn more.


Spoiler alert:

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

answered Apr 23, 2010 at 23:00

Mike Graham's user avatar

Mike GrahamMike Graham

73.5k14 gold badges100 silver badges130 bronze badges

5

Given the following:

a = 23
b = 45
c = 16

round((a/b)*0.9*c)

Running the above outputs an error:

TypeError: 'int' object is not callable.

How can I round the output to an integer?

Mateen Ulhaq's user avatar

Mateen Ulhaq

24k18 gold badges97 silver badges132 bronze badges

asked Mar 19, 2012 at 9:05

rob's user avatar

3

Somewhere else in your code you have something that looks like this:

round = 42

Then when you write

round((a/b)*0.9*c)

that is interpreted as meaning a function call on the object bound to round, which is an int. And that fails.

The problem is whatever code binds an int to the name round. Find that and remove it.

answered Mar 19, 2012 at 9:08

David Heffernan's user avatar

David HeffernanDavid Heffernan

600k42 gold badges1065 silver badges1483 bronze badges

2

I got the same error (TypeError: ‘int’ object is not callable)

def xlim(i,k,s1,s2):
   x=i/(2*k)
   xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x(1-x))
   return xl 
... ... ... ... 

>>> xlim(1,100,0,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in xlim
TypeError: 'int' object is not callable

after reading this post I realized that I forgot a multiplication sign * so

def xlim(i,k,s1,s2):
   x=i/(2*k)
   xl=x*(1-s2*x-s1*(1-x)) / (1-s2*x**2-2*s1*x * (1-x))
   return xl 

xlim(1.0,100.0,0.0,0.0)
0.005

tanks

Duncan Leung's user avatar

answered Jul 17, 2015 at 18:45

Tomate's user avatar

TomateTomate

1951 silver badge5 bronze badges

3

Stop stomping on round somewhere else by binding an int to it.

answered Mar 19, 2012 at 9:07

Ignacio Vazquez-Abrams's user avatar

0

I was also facing this issue but in a little different scenario.

Scenario:

param = 1

def param():
    .....
def func():
    if param:
        var = {passing a dict here}
        param(var)

It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.

Changed function name to something else and it worked.

So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code.
So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.

I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.

bad_coder - on strike's user avatar

answered Mar 4, 2020 at 12:04

Sugandha Jain's user avatar

0

In my case I changed:

return <variable>

with:

return str(<variable>)

try with the following and it must work:

str(round((a/b)*0.9*c))

eyllanesc's user avatar

eyllanesc

233k19 gold badges166 silver badges238 bronze badges

answered Apr 11, 2018 at 17:40

Jonathan Arias's user avatar

Sometimes the problem would be forgetting an operator while calculation.

Example:
print(n-(-1+(math.sqrt(1-4(2*(-n))))/2)) rather
it has to be
print(n-(-1+(math.sqrt(1-4*(2*(-n))))/2))

HTH

answered Jun 12, 2021 at 19:16

Mebatsion Sahle's user avatar

There are two reasons for this error «TypeError: ‘int’ object is not callable«

  1. Function Has an Integer Value

Consider

a = [5, 10, 15, 20]
max = 0
max = max(a)
print(max)

This will produce TypeError: ‘int’ object is not callable.

Just change the variable name «max» to var(say).

a = [5, 10, 15, 20]
var = 0
var = max(a)
print(var)

The above code will run perfectly without any error!!

  1. Missing a Mathematical Operator

Consider

a = 5
b = a(a+1)
print(b)

This will also produce TypeError: ‘int’ object is not callable.

You might have forgotten to put the operator in between ( ‘*’ in this case )

answered Jul 21, 2021 at 9:47

Shambhav Agrawal's user avatar

1

As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.

answered Apr 10, 2020 at 13:20

krishnakeshan's user avatar

krishnakeshankrishnakeshan

1,2222 gold badges14 silver badges18 bronze badges

You can always use the below method to disambiguate the function.

__import__('__builtin__').round((a/b)*0.9*c)

__builtin__ is the module name for all the built in functions like round, min, max etc. Use the appropriate module name for functions from other modules.

answered Sep 12, 2021 at 14:59

Nithish Thomas's user avatar

I encountered this error because I was calling a function inside my model that used the @property decorator.

@property
def volume_range(self):
    return self.max_oz - self.min_oz

When I tried to call this method in my serializer, I hit the error «TypeError: ‘int’ object is not callable».

    def get_oz_range(self, obj):
      return obj.volume_range()

In short, the issue was that the @property decorator turns a function into a getter. You can read more about property() in this SO response.

The solution for me was to access volume_range like a variable and not call it as a function:

    def get_oz_range(self, obj):
      return obj.volume_range # No more parenthesis

answered Jun 25, 2022 at 20:54

Banjoe's user avatar

BanjoeBanjoe

10.4k3 gold badges49 silver badges61 bronze badges

FYI: the 'int' object is not callable error also appears if you accidentally use .size() as a method (which does not exist) instead of the .size property in Pandas dataframes as demonstrated below. Thus the error can appear in unexpected places.

import pandas as pd
s = pd.Series([35, 52, 63, 52])
print("unique numbers: ",s.unique())
print("number of unique values: ",s.unique().size())

answered May 15 at 14:09

w. Patrick Gale's user avatar

Typeerror: int object is not callable – How to Fix in Python

In Python, a “Typeerror” occurs when you use different data types in an operation.

For example, if you attempt to divide an integer (number) by a string, it leads to a typeerror because an integer data type is not the same as a string.

One of those type errors is the “int object is not callable” error.

The “int object is not callable” error occurs when you declare a variable and name it with a built-in function name such as int(), sum(), max(), and others.

The error also occurs when you don’t specify an arithmetic operator while performing a mathematical operation.

In this article, I will show you how the error occurs and what you can do to fix it.

How to Fix Typeerror: int object is not callable in Built-in Function Names

If you use a built-in function name as a variable and call it as a function, you’ll get the “int object is not callable” error.

For instance, the code below attempts to calculate the total ages of some kids with the built-in sum() function of Python. The code resulted in an error because the same sum has already been used as a variable name:

kid_ages = [2, 7, 5, 6, 3]

sum = 0
sum = sum(kid_ages)
print(sum)

Another example below shows how I tried to get the oldest within those kids with the max() function, but I had declared a max variable already:

kid_ages = [2, 7, 5, 6, 3]

max = 0
max = max(kid_ages)
print(max)

Both code examples led to this error in the terminal:
error

To fix the issue, you need to change the name of the variable you named as a built-in function so the code can run successfully:

kid_ages = [2, 7, 5, 6, 3]

sum_of_ages = 0
sum = sum(kid_ages)
print(sum)

# Output: 23
kid_ages = [2, 7, 5, 6, 3]

max_of_ages = 0
max = max(kid_ages)
print(max)

# Output: 7

If you get rid of the custom variables, your code will still run as expected:

kid_ages = [2, 7, 5, 6, 3]

sum = sum(kid_ages)
print(sum)

# Output: 23
kid_ages = [2, 7, 5, 6, 3]

max = max(kid_ages)
print(max)

# Output: 7

How to Fix Typeerror: int object is not callable in Mathematical Calculations

In Mathematics, if you do something like 4(2+3), you’ll get the right answer which is 20. But in Python, this would lead to the Typeerror: int object is not callable error.
ss2-2

To fix this error, you need to let Python know you want to multiply the number outside the parentheses with the sum of the numbers inside the parentheses.

To do this, you do this by specifying a multiplication sign (*) before the opening parenthesis:

print(4*(2+3))

#Output: 20

Python allows you to specify any arithmetic sign before the opening parenthesis.

So, you can perform other calculations there too:

print(4+(2+3))

# Output: 9
print(4-(2+3))

# Output: -1
print(4/(2+3))

# Output: 0.8

Final Thoughts

The Typeerror: int object is not callable is a beginner error in Python you can avoid in a straightforward way.

As shown in this article, you can avoid the error by not using a built-in function name as a variable identifier and specifying arithmetic signs where necessary.

Thank you for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

I’m trying to define a simply Fraction class

And I’m getting 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 code follows:

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 Python doesn’t have method overloading ( function overloading ) so I renamed to get_numerator but that’s not the problems.

What could it be?

SilentGhost's user avatar

SilentGhost

306k66 gold badges305 silver badges292 bronze badges

asked Apr 23, 2010 at 22:29

OscarRyz's user avatar

OscarRyzOscarRyz

196k112 gold badges385 silver badges569 bronze badges

1

You’re using numerator as both a method name (def numerator(...)) and member variable name (self.numerator = n). Use set_numerator and set_denominator for the method names and it will work.

By the way, Python 2.6 has a built-in fraction class.

answered Apr 23, 2010 at 22:31

interjay's user avatar

4

You can’t overload the name numerator to refer to both the member variable and the method. When you set self.numerator = n, you’re overwriting the reference to the method, and so when you call f.numerator(2), it’s trying to do a method call on the member variable, which is an int, and Python doesn’t let you do that. It’s like saying x = 2; x(4) — it just doesn’t make any sense.

You should rename the setter methods to set_numerator and set_denominator to remove this naming conflict.

answered Apr 23, 2010 at 22:32

Adam Rosenfield's user avatar

Adam RosenfieldAdam Rosenfield

389k97 gold badges512 silver badges586 bronze badges

  • You are using numerator as both a method name and a name for an instance attribute. Since methods are stored on the class, when you lookup that attribute you get the number, not the method. (Python will look up attributes on the instance before looking at the class.)

    That is to say that on the line where you say f.numerator(2), it looks up f.numerator and finds that it is 0, then tries to call that 0, which obviously shouldn’t work.

  • If you have any practical purpose for this code, you can use the stdlib fractions module: http://docs.python.org/library/fractions.html

    • This is new in Python 2.6. If I needed to represent fractions but was using an earlier version of Python, I’d probably use sympy’s Rational type.
  • A more practical default value for denominator is probably 1. (That way Fraction(5) would be five, not some undefined operation tending towards infinity.)

  • Rather than a prints method, it would be more typical to define __str__ and just print your object.

  • Your methods are just getting and setting an attribute. In Python, we generally do not use getters and setters—we just let users set our attributes.

    • You’re coming from a Java background, where one of the basic rules is always to use getter and setter methods rather than let users access attributes. The rationale for this rule is that if, at some future date, you needed to do more than just get and set (you needed to process the data), it would require an API change. Since in Python we have properties, we would not need an API change in that instance so we can safely avoid the boilerplate and cruft of setters and getters.
  • It wouldn’t hurt to inherit numbers.Rational (Python 2.6 and up), which lets your class automatically do several things numbers are expected to. You will have to implement everything it needs you to, but then it will automatically make a lot more work. Check out Check out http://docs.python.org/library/numbers.html to learn more.


Spoiler alert:

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

answered Apr 23, 2010 at 23:00

Mike Graham's user avatar

Mike GrahamMike Graham

73.5k14 gold badges100 silver badges130 bronze badges

5

Table of Contents
Hide
  1. What is TypeError: the ‘int’ object is not callable?
  2. Scenario 1: When you try to call the reserved keywords as a function
    1. Solution
  3. Scenario 2: Missing an Arithmetic operator while performing the calculation
    1. Solution
  4. Conclusion

The TypeError: the ‘int’ object is not a callable error occurs if an arithmetic operator is missed while performing the calculations or the reserved keywords are declared as variables and used as functions, 

In this tutorial, we will learn what int object is is not callable error means and how to resolve this TypeError in your program with examples.

There are two main scenarios where developers try to call an integer.

  1. When you try to call the reserved keywords as a function
  2. Missing an Arithmetic operator while performing the calculation

Scenario 1: When you try to call the reserved keywords as a function

Using the reserved keywords as variables and calling them as functions are developers’ most common mistakes when they are new to Python. Let’s take a simple example to reproduce this issue.


item_price = [10, 33, 55, 77]
sum = 0
sum = sum(item_price)
print("The sum of all the items is:", str(sum))

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodemain.py", line 4, in <module>
    sum = sum(item_price)
TypeError: 'int' object is not callable

If you look at the above code, we have declared the sum as a variable. However, in Python, the sum() is a reserved keyword and a built-in method that adds the items of an iterable and returns the sum.

Since we have declared sum as a variable and used it as a function to add all the items in the list, Python will throw TypeError.

Solution

We can fix this error by renaming the sum variable to total_price, as shown below.

item_price = [10, 33, 55, 77]
total_price = 0
total_price = sum(item_price)
print("The sum of all the items is:", str(total_price))

Output

The sum of all the items is: 175

Scenario 2: Missing an Arithmetic operator while performing the calculation

While performing mathematical calculations, if you miss an arithmetic operator within your code, it leads to TypeError: the ‘int’ object is not a callable error.

Let us take a simple example to calculate the tax for the order. In order to get the tax value, we need to multiply total_value*(tax_percentage/100).


item_price = [10, 23, 66, 45]
tax_percentage = 5
total_value = sum(item_price)
tax_value = total_value(5/100)
print(" The tax amount for the order is:", tax_value)

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodemain.py", line 8, in <module>
    tax_value = total_value(5/100)
TypeError: 'int' object is not callable

We have missed out on the multiplication operator while calculating the tax value in our code, leading to TypeError by the Python interpreter.

Solution

We can fix this issue by adding a multiplication (*) operator to our code, as shown below.

item_price = [10, 23, 66, 45]
tax_percentage = 5
total_value = sum(item_price)
tax_value = total_value*(5/100)
print(" The tax amount for the order is:", tax_value)

Output

 The tax amount for the order is: 7.2

Conclusion

The TypeError: the ‘int’ object is not a callable error raised when you try to call the reserved keywords as a function or miss an arithmetic operator while performing mathematical calculations.

Developers should keep the following points in mind to avoid the issue while coding.

  • Use descriptive and unique variable names. 
  • Never use any built-in function, modules, reserved keywords as Python variable names.
  • Ensure that arithmetic operators is not missed while performing calculations.
  • Do not override built-in functions like sum(), round(), and use the same methods later in your code to perform operations.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

  • Ошибка insufficient system storage
  • Ошибка insufficient memory при печати
  • Ошибка installer thread pathfileexists
  • Ошибка installer is no longer responding
  • Ошибка installer integrity check has failed common causes include incomplete