Encapsulation and the ideas behind information hiding
Introduction
One of the key ideas in OO programming is something called 'encapsulation', otherwise know as 'information hiding'. All this means is that a program shouldn't be able to view or change the contents of attributes directly. If a program wants to view a piece of data in an object, it should have to call a method in the object (usually referred to as a 'get method' or 'getter'). The method then goes and gets the data from the object and then passes it back to the code requesting the data. If a program wants to change some data, then they shouldn't be able to do it directly. They should pass the data to a method in the object (called a 'set method' or 'setter'). This will then make the requested changes for the program.
Encapsulation is intended to stop data in an object being accidentally accessed or modified in unintentional ways. This reduces the chance of bugs being introduced to a program. If you can only access data via the get and set methods of an object, those methods can also be used to check for errors, which again, reduces the chance of an error happening.
Up to now, we haven't used encapsulation at all. Consider the following code:
Line 35 is what we are talking about here. We can access any attribute of the object called person1 simply by using the dot notation. According to OO principles, we shouldn't be able to do this important data.
All attributes and all methods are by default 'public' in Python. That means we can access them from anywhere in the program using the dot notation. However, we can make them 'private'. If we put a double score in front of a variable name inside the object, it becomes private. If we tried to access the variable (or a method for that matter) using the dot notation, we would get a message back saying that the variable in the object doesn't exist.
Tasks
Q1. Change line 14 above so it reads self.__strength = strength and then run the code again. What error message do you get?
Q2. Now also change line 35 so it reads person1.__strength += -2 and run the code again. What happens?
Q3. For both Q1 and Q2, you got an error message. Explain why.
Q4. Are all attributes and methods in Python public or private by default?
Q5. How do you make a public attribute private?
Q6. Make the job attribute in the Person class private.
Q7. Add some code to try and print the attribute for job in the person1 object using dot notation.
Q8. Add some code to try and change the job for the person1 object using dot notation.