Setters, Getters and Property deco in a Class
I'm trying to understand the above and have the following code:
class Aclass:
def __init__(self, aval):
print(f'__init__')
self.val = aval
@property
def val(self):
print(f'Getting value _val < {self._val}', end=' ')
return (self._val)
@val.setter
def val(self, aval):
self._val = aval
print(f'Setting value _val > {self._val}')
@property
def newval(self):
self._val = self._val * 10
print(f'Setting newvalue > {self._val}', end=' ')
return (self._val)
def main():
print ('--1--')
myclass = Aclass(37)
print ('--2--')
print (f'...printing val {myclass.val}')
if __name__ == '__main__': main()
When run, I get the following output:
--1--
__init__
Setting value _val > 37
--2--
Getting value _val < 37 ...printing val 37
Some questions and observations:
-
Does the setter always get called when the constructor is initiated ? - it seems to act like a constructor for the __init__ method when self.val is assigned.
-
It throws a recursion error if self.val is set in the setter
-
The name of the setter and the getter (as decorated by '@property) are both linked to the name of the attribute (val).
-
The sequential placement of the methods matter - I get an error if I put the setter before the getter (!?)
I'll post more questions in further comments, (I've left newval in there for further discussion) until then, what are your thoughts? Is this how G/S are used?
thx.
Posted Aug 25, 2020, 12:13 AM UTC
I really don't know what the point of all this is? Python classes don't need setters and getters. You can read and write myclass.val directly.
Also it seems like having a variable and a method with the same name is going to cause problems
Just trying to learn. Thx.