There is not something like a keyword to user encapsulation but you can address the same behavior by using Python convention "_" and "__"
class Example:
def __init__(self):
self.public_var = "public"
self._protected_var = "protected"
self.__private_var = "private"
def public_method(self):
print("This is a public method")
def _protected_method(self):
print("This is a protected method")
def __private_method(self):
print("This is a private method")
# Creating an instance of the class
example_instance = Example()
# Accessing public method and variable
example_instance.public_method()
print(example_instance.public_var)
# Accessing protected method and variable
example_instance._protected_method()
print(example_instance._protected_var)
# Trying to access private method and variable (will raise AttributeError)
# example_instance.__private_method()
# print(example_instance.__private_var)
The class Example
has three types of methods and variables:
- Public methods and variables are accessible from outside the class.
- Protected methods and variables have a single underscore
_
prefix and are typically considered non-public, although Python does not enforce this.
- Private methods and variables have a double underscore
__
prefix and are only accessible within the class itself.
In the example code:
-
public_var
, public_method()
, _protected_var
, and _protected_method()
are respectively public and protected variables and methods.
-
_protected_var
and _protected_method()
can be accessed from outside the class but are typically considered non-public.
-
__private_var
and __private_method()
are private variables and methods and can only be accessed within the class itself. Trying to access them from outside the class will raise an AttributeError
.