TypeError: 'int' object is not callable- Sorry if AP

774 Views Asked by At
class Car:
    # constructor
    def __init__(self, make, model, year, mpg):
        # instance variables
        self.carMake = make
        self.carModel=model
        self.carYear = year
        self.efficiency=mpg
        self.gas = 0

    # special method
    def __str__(self):
        return "%s %s %s"%(self.carYear, self.carMake, self.carModel)

    def refuel(self,gallon):
        if gallon < 0:
            print("Sorry, amount cannot be negative")
        else:
            self.gas=self.gas+gallon
            print (self.gas)
            print("Added %.2f gallon of gas to the tank"%(self.gas))

    def gas(self):
        print(self.gas)


> Traceback (most recent call last):   File "<pyshell#12>", line 1, in
> <module>
>     c1.gas() TypeError: 'int' object is not callable
3

There are 3 best solutions below

0
On

You have self.gas initialized to an int in the __init__() method, but then you define a method named gas() as well. Once __init__() runs, self.gas is an int. I'm guessing somewhere you are calling gas() on an instance of this class.

Rename your gas() method to something like print_gas(), or, wherever you're calling this, instead of doing c1.gas(), just do print c1.gas.

0
On

Consider this class Test in a file called test.py:

class Test:
    def __init__(self):
        self.x=3
    def x(self):
        print self.x

Now I import class Test in my console and see what methods it has:

>>> from test import Test
>>> [method for method in dir(Test) if callable(getattr(Test, method))]
['__init__', 'x']

Notice that it has the method x. Now let's create an instance of Test

>>> k=Test()

Let's see what methods we have

>>> [method for method in dir(k) if callable(getattr(k, method))]
['__init__']
>>>

As you can see the method x is no longer available. why?

When you created k as an instance of Test, it executes the __init__ method and sees self.x=3 which redefines x to be just a variable in self and your method x() is gone. So when you do k.x() it thinks that you are doing it on self.x that you set in __init__ which is not callable. However just k.x will work as I show below:

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

The conclusion is don't name your variables and methods the same.

0
On

Your method gas and your instance attribute gas created in __init__ have the same name. The method is stored on the class, but is "shadowed" by the attribute stored on the instance, since Python first looks for names on the instance, then on the class and its parents.

So self.gas is an integer and you can't call it.