3

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?

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

2 Answers2

3

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
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
2

it is a property! that means that when you get it as an attribute it is the return value, if you want it to be a method then don't make it a property.

to use a property just use foo.Bar and it will return the value.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59