Lesson 03 - Accessors & Mutators
Lesson 03 - Accessors & Mutators
• Classes and objects are more like the real world. They
minimize the semantic gap by modeling the real world
more closely
Gives Error
Hiding your private parts (in Python)
• Be a little sneakier then.. use __name:
Hiding your private parts (in Python)
• Be super sneaky then.. use _Student__name:
Hiding your private parts (in Python)
• So, it is possible to interact with private data in
Python, but it is difficult to hide them
completely and good programers know not to
do it.
• Using the defined interface methods (getters
and setters) will make code more
maintainable and safer to use. Setters and
getters provide abstraction.
Getters & Setters (or)
Accessors & Mutators
• These methods are a coding convention
• Getters/Accessors are methods that return an
attribute
def get_name(self):
• Setters/Mutators are methods that set an
attribute
def set_name(self,newName):
Why use getters?
• Definition of my getter:
def getName(self):
return self.name
• What if I want to store the name instead as first
and last name in the class? Well, with the getter
I only have to do this:
def getName(self):
return self.firstname + self.lastname
Why use getters?
• If I had used dot notation outside the class,
then all the code OUTSIDE the class would
need to be changed because the internal
structure INSIDE the class changed.
def __private_method(self):
print('This is a private method.')