Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'int' object is not callable error python

Tags:

python

int

Hey guys so I am getting this "TypeError: 'int' object is not callable" error when I run this code, I did some research and I think it's something with my variable naming? Could someone please explain to me what is wrong?

class account(object):
    def set(self, bal):
        self.balance = bal
    def balance(self):
        return balance

Here is my example run:

>>> a = account()
>>> a.set(50)
>>> a.balance()
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    a.balance()
TypeError: 'int' object is not callable
like image 901
user12074577 Avatar asked Jun 11 '26 17:06

user12074577


1 Answers

You are masking your method balance with a instance attribute balance. Rename one or the other. You could rename the instance attribute by pre-pending it with an underscore for example:

def set(self, bal):
    self._balance = bal

def balance(self):
    return self._balance

Attributes on the instance trump those on the class (except for data descriptors; think propertys). From the Class definitions documentation:

Variables defined in the class definition are class attributes; they are shared by instances. Instance attributes can be set in a method with self.name = value. Both class and instance attributes are accessible through the notation “self.name”, and an instance attribute hides a class attribute with the same name when accessed in this way.

like image 113
Martijn Pieters Avatar answered Jun 13 '26 05:06

Martijn Pieters