While learning thru advanced tutorials, it’s time to consolidate some basic concepts in Python. The explanation about property at https://www.programiz.com/python-programming/property is very clear. I’m writing an example below to remind myself of the private variable _cm being a convention only. Name like temp_cm works too.
Also cm is no longer a normal instance variable when property decorator is used. The design of adding @property allows backward compatible to keep codes unchanged!
class Unit:
def __init__(self, cm=0):
self.cm = cm
def toInch(self):
return self.cm * 0.3937
# @property
# def cm(self):
# return self.temp_cm
#
# @cm.setter
# def cm(self, v):
# self.temp_cm = v
unit = Unit(cm=100)
print(unit.__dict__)
# {'cm': 100} Without getter setter. The old way.
# {'temp_cm': 100} With getter setter. The code still runs. It's backward compatible !