Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a class member function gives TypeError [duplicate]

Tags:

python

I am working with a library which has the following code for a Python class (edited by myself to find a minimal working example):

class Foo(object):

  def __init__(self):
    self._bar = 0

  @property
  def Bar(self):
    return self._bar

If I then run the following:

foo = Foo()
x = foo.Bar()

I get an error message:

TypeError: 'int' object is not callable

So, it seems the error is telling me that it thinks Bar() is an int, rather than a function. Why?

like image 875
Karnivaurus Avatar asked May 16 '26 23:05

Karnivaurus


1 Answers

foo.Bar is the correct way to use

property converts the class method into a read only attribute.

class Foo(object):

      def __init__(self):
        self._bar = 0

      @property
      def Bar(self):
        return self._bar

      @Bar.setter
      def Bar(self, value):
        self._bar = value


foo = Foo()
print(foo.Bar)  # called Bar getter
foo.Bar = 10  # called Bar setter
print(foo.Bar)  # called Bar getter
like image 66
Haifeng Zhang Avatar answered May 18 '26 13:05

Haifeng Zhang