Advanced Lesson 3
Advanced Object-Oriented Programming
Chapter 3: Encapsulation
Property
What if you also want to be able to update the .name
property (in a controlled manner, of course!)
lovely_person.name = "George"
All you need to do is to convert the setter method set_name()
into a name
property. Again, you rename set_name()
to name()
(Line 10) and annotate the method with a @name.setter
decorator (Line 9), where @name
is the name of your property. Also notice that I’ve changed the constructor back to how it was before (Line 3)
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 |
|
Now, users of your VainPerson
class can both read and write to the name
property (in a controlled manner), and you also made your code more readable in the process!