Advanced Lesson 2
Advanced Object-Oriented Programming
Chapter 3: Encapsulation
Setter methods
Let’s say that VainPerson
now also allows someone to change its name. However, VainPerson
will only allow their name to be changed if they like the sound of the new name. The name must also always be stored in uppercase (VainPerson
is upper-class after all!)
Again, you can allow an outsider to modify your non-public attributes in a controlled manner via a method. Such methods are usually called setter methods in OOP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
The set_name()
method (Line 8) allows an outsider to set the __name
attribute without exposing it, but in a controlled manner. I have also updated Line 3 which also uses the method to set the name correctly, rather than setting self.__name = name
directly in the constructor.
In Line 26, you can see that __name
is stored in uppercase.
Line 27 does not update __name
because VainPerson
does not like it!
Line 29 is successful, so __name
is now "GEORGE"
.
Lines 31-32 are just to demonstrate my point from the previous page, that lovely_person.__name
is a new attribute, and is different from the name-mangled self.__name
in the definition. So the ‘real’ __name
is still "GEORGE"
.