I was trying to read about getters and setters in python2 and python3. Started experimenting with this: https://stackoverflow.com/a/16200745/5161197
class Foo():
def __init__(self):
self._spam = 0
#@property
#def spam(self):
# print("in the getter: ")
# return self._spam
#@spam.setter
#def spam(self, move):
# print("in the setter: ")
# self._spam = move + self._spam
f = Foo()
f.spam = 2
print(f.spam)
When I run the code using python2
$ python2 ok.py
2
When I run the code using python3
$ python3 ok.py
2
I was shocked to see the code not throwing AttributeError since spam is not defined anywhere. Note that property and setter code was commented out. Can someone explain how does it work?
The next experiment was to run the actual code in the link (with getter and setter).
With python2, the output was
$ python ok.py
2
With python3, the output was
$ python3 ok.py
in the setter:
in the getter:
2
So, it seems the property and setter have no role in python2 but work in python3. Can someone please clarify this?
Python version on my Mac-OS
$ python --version
Python 2.7.5
$ python3 --version
Python 3.6.8