Also an of aspect @property decorator is that original implementation can be made backward compatible.
So to give a example.
class Student:
def __init__(self, forename):
self.forename = forename
# Original way of doing it
>>> s1 = Student("billy")
# Get
>>> s1.forename
'billy'
# Set
>>> s1.forename = 'Kent'
>>> s1.forename
'Kent'
So a new silly rule is that forename can not be longer than 10 character.
Let say Kent that has been working with Java for many years he know how to do this task just put in getter/setters
class Student:
def __init__(self, forename):
self.set_forename(forename)
# getter method
def get_forname(self):
return self.forename
# setter method
def set_forename(self, name):
if len(name) > 10:
raise ValueError("Forename to long need to be less than 10 character")
self.forename = name
>>> s1 = Student("billy")
>>> s1.get_forname()
'billy'
>>> s1.set_forename('Kent')
>>> s1.get_forname()
'Kent'
>>> s1.set_forename('Constantine')
Traceback (most recent call last):
File ".....py", line 12, in set_forename
raise ValueError("Forename to long need to less than 10 character ")
ValueError: Forename to long need to less than 10 character
So this works,but the original implementation way of doing this is broken.
Mary that has been doing this for 20-year is upset and cry
that can not use
s1.forename = 'forename'
way anymore.
So Billy that has been working some time in Python don't want to make Mary cry.
class Student:
def __init__(self, forename):
self.forename = forename
@property
def forename(self):
return self._forename
@forename.setter
def forename(self, name):
if len(name) > 10:
raise ValueError("Forename to long need to less than 10 character")
self._forename = name
>>> s1 = Student("billy")
>>> s1.forename
'billy'
>>> s1.forename = 'Kent'
>>> s1.forename
'Kent'
>>> s1.forename = 'Constantine'
Traceback (most recent call last):
File "......py", line 12, in forename
raise ValueError("Forename to long need to be less than 10 character")
ValueError: Forename to long need to less than 10 character
Now can use original implementation with the new feature working,and Mary is happy