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
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