Advanced Lesson 2
Advanced Object-Oriented Programming
Chapter 3: Encapsulation
Getter methods
Let’s say that VainPerson
does allow someone to know its name (how would you address it otherwise?) But it wishes to always be addressed by a long majestic title. You can do this with a method that retrieves its __name
, but exposes the __name
in a controlled manner. These are often called getter methods in OOP.
class VainPerson:
def __init__(self, name):
self.__name = name
def get_name(self):
return f"Your Most Honourable Excellency {self.__name}"
lovely_person = VainPerson("Edward")
print(lovely_person.get_name()) # Your Most Honourable Excellency Edward