Recall & Review
beginner
What is name mangling in Python?
Name mangling is a way Python changes the name of class attributes that start with two underscores (__). It helps avoid name conflicts in subclasses by making the attribute name unique to the class.Click to reveal answer
beginner
How does Python transform a variable named
__var inside a class MyClass?Python changes <code>__var</code> to <code>_MyClass__var</code> internally. This makes it harder to accidentally access or override it from outside the class or in subclasses.Click to reveal answer
intermediate
Why does Python use name mangling instead of making variables truly private?
Python follows a philosophy of 'we are all consenting adults'. Name mangling is a gentle way to avoid accidental access but does not make variables truly private. Programmers can still access mangled names if needed.
Click to reveal answer
beginner
What happens if a variable name starts with a single underscore
_var instead of double underscores?A single underscore is a convention to indicate 'internal use' but Python does not change the name. It is just a hint to programmers, not enforced by the language.
Click to reveal answer
intermediate
Can name mangling prevent all access to a variable?
No. Name mangling only changes the variable name to include the class name. You can still access it by using the mangled name directly. It is meant to avoid accidental access, not to enforce strict privacy.Click to reveal answer
What prefix triggers name mangling in Python class attributes?
✗ Incorrect
Only variables starting with double underscores are name mangled by Python.
If a class is named
Car and has an attribute __speed, what is the mangled name?✗ Incorrect
Python changes __speed to _Car__speed by adding an underscore and the class name.
What is the main purpose of name mangling?
✗ Incorrect
Name mangling helps avoid accidental overwriting or access in subclasses, not full privacy.
Can you access a mangled variable from outside the class?
✗ Incorrect
You can access it if you know the mangled name, but it is discouraged.
What does a single underscore prefix (e.g., _var) mean in Python?
✗ Incorrect
A single underscore is a hint to programmers that the variable is for internal use, but Python does not enforce it.
Explain what name mangling is and why Python uses it.
Think about how Python changes variable names inside classes.
You got /4 concepts.
Describe the difference between a single underscore prefix and a double underscore prefix in Python variable names.
Consider how Python treats each prefix differently.
You got /4 concepts.