In-Depth Python OOP
In-Depth Python OOP
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.
Parent. Within the
Parentclass, there is a private attribute called
__attribute. Private attributes in Python are denoted by a double underscore prefix.
Parentclass also has a method called
get_from_parentthat attempts to print the value of the private attribute
Next, a subclass called
Childis defined, which inherits from the
Childclass has a method called
get_from_child, which also attempts to print the value of the private attribute
An instance of the
Childclass is created using
instance = Child(). When the
get_from_parentmethod 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_childmethod 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
Childclass does not have direct access to the private attribute
__attributedefined in 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.
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?