What are public, protected and private attributes in Python?
Python has no strict access control like Java or C++. Instead it uses naming rules to show how an attribute should be used.
| Name | Type | Meaning |
|---|---|---|
name | Public | Can be used from anywhere |
_name | Protected | By convention only for the class and its child classes. Python does not stop you |
__name | Private | Python renames it (name mangling), so it cannot be reached by its normal name from outside |
class Account:
def __init__(self):
self.owner = "Robin"
self._balance = 100
self.__pin = 1234
a = Account()
print(a.owner)
print(a._balance)
print(a.__pin)
Output:
Tutorials Class - Output Window
Robin
100
AttributeError: 'Account' object has no attribute '__pin'
The private attribute is stored as _Account__pin behind the scenes, so it is hidden from casual use but not truly secret. See Python Access Modifiers for more.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |