Bird
Raised Fist0
Pythonprogramming~5 mins

Name mangling in Python - Cheat Sheet & Quick Revision

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

      Practice

      (1/5)
      1. What does name mangling do to an attribute starting with double underscores in a Python class?
      easy
      A. It adds the class name before the attribute name to avoid conflicts.
      B. It makes the attribute public and accessible everywhere.
      C. It deletes the attribute from the class.
      D. It converts the attribute name to uppercase.

      Solution

      1. Step 1: Understand double underscore prefix

        Attributes starting with double underscores trigger name mangling in Python classes.
      2. Step 2: Effect of name mangling

        Python adds the class name before the attribute name to avoid accidental access or conflicts.
      3. Final Answer:

        It adds the class name before the attribute name to avoid conflicts. -> Option A
      4. Quick Check:

        Name mangling = adds class name prefix [OK]
      Hint: Double underscores add class name prefix to attribute [OK]
      Common Mistakes:
      • Thinking double underscores make attribute public
      • Confusing name mangling with deleting attributes
      • Assuming attribute name changes to uppercase
      2. Which of the following is the correct way to define a private attribute using name mangling in a Python class?
      easy
      A. self.__my_attr = 5
      B. def __my_attr(self): pass
      C. self._my_attr = 5
      D. self.my_attr__ = 5

      Solution

      1. Step 1: Identify private attribute syntax

        Private attributes use double underscores at the start of the name, like __my_attr.
      2. Step 2: Check correct assignment

        Assigning with self.__my_attr = 5 correctly defines a private attribute with name mangling.
      3. Final Answer:

        self.__my_attr = 5 -> Option A
      4. Quick Check:

        Double underscore prefix = private attribute [OK]
      Hint: Use double underscores before attribute name for private [OK]
      Common Mistakes:
      • Using single underscore instead of double
      • Placing underscores after attribute name
      • Defining private attribute as a method incorrectly
      3. What will be the output of this code?
      class A:
          def __init__(self):
              self.__x = 10
      
      a = A()
      print(hasattr(a, '__x'))
      print(hasattr(a, '_A__x'))
      medium
      A. True\nTrue
      B. False\nTrue
      C. True\nFalse
      D. False\nFalse

      Solution

      1. Step 1: Check attribute __x existence

        Due to name mangling, __x is stored as _A__x internally, so hasattr(a, '__x') returns False.
      2. Step 2: Check mangled attribute _A__x existence

        hasattr(a, '_A__x') returns True because this is the mangled name storing the value.
      3. Final Answer:

        False True -> Option B
      4. Quick Check:

        __x hidden as _A__x = False, True [OK]
      Hint: Check mangled name with _ClassName__attr [OK]
      Common Mistakes:
      • Assuming __x is directly accessible
      • Confusing mangled name with original
      • Expecting both hasattr calls to be True
      4. What is the error in this code snippet?
      class B:
          def __init__(self):
              self.__val = 5
      
      b = B()
      print(b.__val)
      medium
      A. SyntaxError due to double underscores
      B. No error, prints 5
      C. TypeError because __val is private
      D. AttributeError because __val is name mangled

      Solution

      1. Step 1: Understand name mangling effect

        __val is mangled to _B__val internally, so b.__val does not exist.
      2. Step 2: Accessing __val causes AttributeError

        Trying to print b.__val raises AttributeError because the attribute is hidden by name mangling.
      3. Final Answer:

        AttributeError because __val is name mangled -> Option D
      4. Quick Check:

        Accessing __val directly = AttributeError [OK]
      Hint: Access mangled attribute with _ClassName__attr [OK]
      Common Mistakes:
      • Expecting no error when accessing __val
      • Thinking double underscores cause syntax error
      • Confusing AttributeError with TypeError
      5. Given this class:
      class C:
          def __init__(self):
              self.__data = 42
          def get_data(self):
              return self.__data
      
      c = C()

      How can you access the private attribute __data from outside the class without using the get_data method?
      hard
      A. c.__data
      B. c._data
      C. c._C__data
      D. c.get_data()

      Solution

      1. Step 1: Understand name mangling for __data

        The attribute __data is stored internally as _C__data due to name mangling.
      2. Step 2: Access mangled attribute directly

        You can access it from outside the class using c._C__data.
      3. Final Answer:

        c._C__data -> Option C
      4. Quick Check:

        Access private with _ClassName__attr [OK]
      Hint: Use _ClassName__attr to access private attribute [OK]
      Common Mistakes:
      • Trying to access c.__data directly
      • Using single underscore _data instead
      • Confusing method call with attribute access