name mangling
Python's renaming of a class attribute whose name starts with two underscores to _ClassName__name.
In more detail
Inside a class body, a name such as __balance that starts with two underscores and does not end with two is stored as _Account__balance. Code outside the class cannot reach it by the plain name, but the mangled name still works, so it prevents accidents rather than providing security. An assignment to obj.__balance written outside the class is not mangled and creates a separate attribute.
Example
class Account:
def __init__(self):
self.__balance = 500
print(Account()._Account__balance) # 500Related terms
- class attribute — An attribute defined in the class body, shared by every instance of the class.
- __dict__ — The dictionary that holds an object's own attributes, or a class's own attributes.
- instance attribute — An attribute stored on one instance, usually set as self.name = value, so each instance has its own copy.
Taught in
- Your Own Modules And Packages — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Class Variables, Instance Variables And __dict__ — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Object-Oriented Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Mock, Review And Exam Day — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep