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.
99
1
2
3
4
5
6
7
8
9
10
11
12
13
class Parent:
__attribute = "Private"
def get_from_parent(self):
print(self.__attribute)
class Child(Parent):
def get_from_child(self):
print(self.__attribute)
instance = Child()
instance.get_from_parent()
instance.get_from_child() # AttributeError
12345678910111213class Parent: __attribute = "Private" def get_from_parent(self): print(self.__attribute) class Child(Parent): def get_from_child(self): print(self.__attribute) instance = Child() instance.get_from_parent() instance.get_from_child() # AttributeError
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:
pythoninstance._ClassName__attribute
But this is a BAD PRACTICE that specific syntax tells us.
Look at the example:
9
1
2
3
4
5
6
7
class SomeClass:
__value = "Privated value"
instance = SomeClass()
print(instance._SomeClass__value)
print(SomeClass._SomeClass__value)
1234567class SomeClass: __value = "Privated value" instance = SomeClass() print(instance._SomeClass__value) print(SomeClass._SomeClass__value)
Everything was clear?
Thanks for your feedback!
Section 3. Chapter 4
Ask AI
Ask anything or try one of the suggested questions to begin our chat