Ticker

6/recent/ticker-posts

Python Access Modifiers

Python Access Modifiers

Access modifiers in Python are used to control the visibility and accessibility of class members (attributes and methods). They help in enforcing encapsulation and data hiding, ensuring that certain attributes or methods can only be accessed by specific parts of the code.

There are three types of access modifiers in Python:

  1. Public: Members declared as public are accessible from anywhere, both within the class and outside the class.
python
class MyClass:
def __init__(self):
self.public_var = 10

def public_method(self):
return "This is a public method."

obj = MyClass()
print(obj.public_var) # Output: 10
print(obj.public_method()) # Output: This is a public method.
  1. Protected: Members declared as protected are accessible within the class and its subclasses (inherited classes), but not outside the class.
python
class MyClass:
def __init__(self):
self._protected_var = 20

def _protected_method(self):
return "This is a protected method."

class SubClass(MyClass):
def access_protected(self):
return self._protected_var, self._protected_method()

obj = SubClass()
print(obj.access_protected()) # Output: (20, 'This is a protected method.')
  1. Private: Members declared as private are accessible only within the class. They are not accessible from outside the class, not even from its subclasses.
python
class MyClass:
def __init__(self):
self.__private_var = 30

def __private_method(self):
return "This is a private method."

def access_private(self):
return self.__private_var, self.__private_method()

obj = MyClass()
print(obj.access_private()) # Output: (30, 'This is a private method.')

Remember that access modifiers in Python are not strict like some other languages (e.g., C++ or Java), and their usage relies on developer conventions to respect encapsulation and data hiding principles.

Post a Comment

0 Comments