Consider this Python class with a private attribute. What happens when we try to print it directly?
class MyClass: def __init__(self): self.__secret = 'hidden' obj = MyClass() print(obj.__secret)
Private attributes are not accessible directly outside the class.
In Python, attributes with double underscores are name-mangled and cannot be accessed directly outside the class, causing an AttributeError.
Given a class with a private attribute, what is the output when accessing it using name mangling?
class MyClass: def __init__(self): self.__secret = 'hidden' obj = MyClass() print(obj._MyClass__secret)
Private attributes are stored with a name that includes the class name.
Python changes the name of private attributes by prefixing them with _ClassName, so accessing obj._MyClass__secret works.
Look at this code where a subclass tries to modify a private attribute of its parent. What is printed?
class Parent: def __init__(self): self.__value = 10 class Child(Parent): def __init__(self): super().__init__() self.__value = 20 obj = Child() print(obj._Parent__value)
Private attributes are name-mangled per class, so subclass private attributes are different.
The Child class creates its own private attribute _Child__value, so _Parent__value remains 10.
What happens when you try to access an attribute with a single underscore prefix from outside the class?
class MyClass: def __init__(self): self._hidden = 'secret' obj = MyClass() print(obj._hidden)
Single underscore means 'protected' by convention, but no real restriction.
Attributes with a single underscore are accessible outside the class; it's just a convention to treat them as non-public.
Choose the best explanation for why Python uses name mangling (double underscore prefix) for private attributes.
Think about how subclasses might accidentally overwrite attributes.
Python's name mangling changes attribute names to include the class name, avoiding accidental overwrites in subclasses but does not enforce strict privacy.