Python Practice › OOP Programs › Program 24

Protected and private members

EasyOOP Programs · 24 of 48

Write a Python program showing protected (_x) and private (__x) members.

Advertisement
Output
asha tester
['name', '_role', '_User__password']

Approach

  1. One underscore is a convention; two underscores trigger name mangling.

Solution

Python
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.

More oop programs

← All 48 OOP Programs

Leave a Comment