0

I'm probably missing something really simple here.

I'm trying to use property() to add getter and setter functions to an attribute of MyClass.

class MyClass:
    def __init__(self, attr):
        self._attr = attr

        def attr_setter(self, value):
            print(f'Setting attr')
            self._attr = value

        def attr_getter(self):
            print('Getting attr')
            return self._attr

        self.attr = property(fget=attr_getter, fset=attr_setter)

c = MyClass('something')
print(c.attr)
c.attr = 'something else'
print(c.attr)

However, the print statements and the assignment do not trigger attr_setter and attr_getter. I get the following output:

property object at <0x0000024A26B489A0>
something else

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 3
    Did you pasted wrongly or `attr_setter` & `attr_getter` inside `__init__`, which is wrong – Epsi95 Jul 10 '21 at 15:43
  • 1
    Does this answer your question? [How does the @property decorator work in Python?](https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work-in-python) – quamrana Jul 10 '21 at 15:44
  • @Epsi95 I did not past it wrongly, I thought the right way to go would be to place those functions inside of `__init__`. Thanks! – Felipe Martins Jul 10 '21 at 15:54
  • @quamrana Thanks for the link. I had already read quite a bit about `@property`, but even with that I didn't realize the functions should go outside the `__init__` call. – Felipe Martins Jul 10 '21 at 15:57

1 Answers1

1

Find the details in comment

class MyClass:
    def __init__(self, attr):
        #self._attr = attr --> you might want to call the setter
        self.attr_setter(attr)
    
    # correcting the indentation
    def attr_setter(self, value):
        print(f'Setting attr')
        self._attr = value

    def attr_getter(self):
        print('Getting attr')
        return self._attr

    attr = property(fget=attr_getter, fset=attr_setter)

c = MyClass('something')  #Setting attr
print(c.attr) #Getting attr something
c.attr = 'something else' #Setting attr
print(c.attr) #Getting attr something else

# Setting attr
# Getting attr
# something
# Setting attr
# Getting attr
# something else
Epsi95
  • 8,832
  • 1
  • 16
  • 34