Search⌘ K

Puzzle 7: Explanation

Explore how Python handles attribute privacy through name mangling, allowing classes to protect variables by automatically renaming them. Understand how this convention helps avoid attribute conflicts in subclasses and improves code organization.

We'll cover the following...

Try it yourself

Try executing the code below to verify the result:

Python 3.8
next_uid = 1
class User:
def __init__(self, name):
global next_uid
self.name = name
self.__id = next_uid
next_uid += 1
u = User('daffy')
print(f'name={u.name}, id={u.__id}')

Explanation

Unlike other languages, Python does not have private and protected attributes. By convention, if we prefix our attributes or variables with an underscore, like this _, the attributes are considered ...