Course Content
In-Depth Python OOP
4. Polymorphism and Abstraction
In-Depth Python OOP
Private
The private access modifier is used to encapsulate attributes and methods within a class. Private attributes and methods are not accessible to subclasses and are intended to be used only within the class itself. They provide a way to hide implementation details and enforce encapsulation.
Code Description
The code defines a class called
The
Next, a subclass called
An instance of the
However, when the
Therefore, the code demonstrates that private attributes are encapsulated within the class, not accessible to subclasses, and intended for use only within the class itself. They provide a way to hide implementation details and enforce encapsulation, ensuring that the attribute is only accessible within the class that defines it.
Parent
. Within the Parent
class, there is a private attribute called __attribute
. Private attributes in Python are denoted by a double underscore prefix.The
Parent
class also has a method called get_from_parent
that attempts to print the value of the private attribute __attribute
using print(self.__attribute)
.Next, a subclass called
Child
is defined, which inherits from the Parent
class. The Child
class has a method called get_from_child
, which also attempts to print the value of the private attribute __attribute
using print(self.__attribute)
.An instance of the
Child
class is created using instance = Child()
. When the get_from_parent
method is called on this instance using instance.get_from_parent()
, it successfully prints the value of the private attribute __attribute
. This is because private attributes are accessible within the class where they are defined.However, when the
get_from_child
method is called on the same instance using instance.get_from_child()
, it raises an AttributeError
. This is because private attributes are not accessible to subclasses. The Child
class does not have direct access to the private attribute __attribute
defined in the Parent
class.Therefore, the code demonstrates that private attributes are encapsulated within the class, not accessible to subclasses, and intended for use only within the class itself. They provide a way to hide implementation details and enforce encapsulation, ensuring that the attribute is only accessible within the class that defines it.
You can utilize parent methods to access parent private attributes/methods, which helps in reducing dependencies.
Python is a highly flexible programming language, allowing you to access private attributes using the following syntax:
But this is a BAD PRACTICE that specific syntax tells us.
Look at the example:
How to define private attribute?
Select the correct answer
Everything was clear?
Section 3. Chapter 4