Python Practice › OOP Programs › Program 24
Protected and private members
Write a Python program showing protected (_x) and private (__x) members.
Output
asha tester ['name', '_role', '_User__password']
Approach
- One underscore is a convention; two underscores trigger name mangling.
Solution
class User: def __init__(self): self.name = "asha" self._role = "tester" self.__password = "s3cret" u = User()print(u.name, u._role)print([a for a in vars(u)])Output
asha tester ['name', '_role', '_User__password']
Line by line
Line 9
The private attribute is stored as _User__password, which is why outside code cannot use u.__password.
Learn the concept
New to this topic? Read the lesson, then come back.