Public and Private Members

Naming conventions for access control

Interview Relevant: Python conventions

Public and Private Members

Python uses conventions for access control.

Code Examples

Access control conventions.

python
1class BankAccount:
2    def __init__(self, balance):
3        self.owner = "John"      # Public
4        self._balance = balance  # Protected (convention)
5        self.__pin = "1234"      # Private (name mangling)
6
7account = BankAccount(1000)
8print(account.owner)        # Public - accessible
9print(account._balance)     # Protected - discouraged
10# print(account.__pin)      # AttributeError!
11print(account._BankAccount__pin)  # Name mangled

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In