In Python, you can access and modify the attributes of an object directly, using dot notation.
However, it is generally a good object-oriented programming practice to access and modify the attributes of an object through their getters, setters, and deleters, rather than directly using dot notation. This is because using getters, setters, and deleters can give you more control over how the attributes are accessed and modified, and can make your code more readable and easier to understand.
For example, the following example defines a setter method for the attribute _score to limit the range of its value:
xxxxxxxxxx
class Student:
def __init__(self):
self._score = 0
def set_score(self, s):
if 0 <= s <= 100:
self._score = s
else:
raise ValueError('The score must be between 0 ~ 100!')
Yang = Student()
Yang.set_score(100)
print(Yang._score)
# 100
class Student:
def __init__(self):
self._score = 0
@property
def score(self):
return self._score
@score.setter
def score(self, s):
if 0 <= s <= 100:
self._score = s
else:
raise ValueError('The score must be between 0 ~ 100!')
@score.deleter
def score(self):
del self._score
Yang = Student()
Yang.score=99
print(Yang.score)
# 99
Yang.score = 999
# ValueError: The score must be between 0 ~ 100!
works as expected. However, the above implementation seems not elegant enough.
It would be better if we can modify the attribute like a normal attribute using dot notation but still has the limitations, rather than having to call the setter method like a function.
This is why Python provides a built-in decorator named @propery. Using it, we can modify attributes using dot notation directly. It will improve the readability and elegance of our code.
Now, let’s change the previous program a bit: