class Car: def __init__(self, model): self._model = model car = Car('Tesla') print(car._model)
In Python, attributes with a single underscore (e.g., _model) are protected by convention but still accessible directly. So, car._model prints the value 'Tesla'.
class Animal: def __init__(self): self._sound = 'Roar' class Lion(Animal): def make_sound(self): return self._sound lion = Lion() print(lion.make_sound())
The subclass Lion can access the protected attribute _sound from its parent Animal. So, lion.make_sound() returns 'Roar'.
class Secret: def __init__(self): self.__hidden = 'hidden_value' s = Secret() print(hasattr(s, '__hidden')) print(hasattr(s, '_Secret__hidden'))
Attributes with double underscores are renamed internally to include the class name. So, __hidden becomes _Secret__hidden. The first hasattr returns False, the second True.
In Python, a single underscore prefix is a convention to indicate an attribute is protected. It is not enforced by the language, so the attribute can be accessed outside the class but should be treated as non-public.
class Box: def __init__(self): self._content = 'secret' @property def content(self): return self._content b = Box() print(b.content) print(b._content)
The property content returns the protected attribute _content. Both b.content and b._content print 'secret'.