0
0
Pythonprogramming~5 mins

Name mangling in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ANo underscore
BSingle underscore (_)
CDouble underscore (__)
DTriple underscore (___)
If a class is named Car and has an attribute __speed, what is the mangled name?
A__Car_speed
Bspeed__Car
C_speed__Car
D_Car__speed
What is the main purpose of name mangling?
ATo avoid accidental name conflicts in subclasses
BTo make variables completely private
CTo speed up variable access
DTo encrypt variable names
Can you access a mangled variable from outside the class?
AYes, by using the mangled name
BNo, it is impossible
COnly inside the class
DOnly in subclasses
What does a single underscore prefix (e.g., _var) mean in Python?
AIt deletes the variable
BIt is a convention for internal use only
CIt makes the variable public
DIt triggers name mangling
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.