0

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
likecs
  • 353
  • 2
  • 13
  • 1
    "I was shocked to see the code not throwing AttributeError since spam is not defined anywhere" It is definitely defined right here: `f.spam = 2`. – juanpa.arrivillaga Feb 23 '22 at 21:57
  • 1
    "So, it seems the property and setter have no role in python2 " They do, but in Python 2, you have to use a "new-style" class, so you must inherit from `object` explicitly. This distinction doesn't exist in Python 3, *everything* is a "new style" class and inheriting from `object` happens implicitly if you dont' do it explicitly. Note, Python 2 is passed it's official end of life, and is no longer officially supported. These distinctions are just historical curiosities, unless you are maintaining an old Python 2 code base (run!) – juanpa.arrivillaga Feb 23 '22 at 21:59
  • 1
    In any case, the *important* less about getters and setters in Python is **you definitely shouldn't be writing them**. What you are actually showing above are "properties", that in effect, allow you to avoid having to write boilerplate `get_x` and `set_x` methods ("actual" getters and setters) and maintain encapsulation with just regular attribute access syntax. – juanpa.arrivillaga Feb 23 '22 at 22:01
  • Thank you @juanpa.arrivillaga. It is clear now. Yeah, I am trying to see the differences between python2 and 3 for the porting part. – likecs Feb 24 '22 at 09:00

0 Answers0