How does Python handle access modifiers for class members (attributes and methods)?
Answer:
Explanation:
Python handles access modifiers using naming conventions rather than explicit keywords. By convention, a single underscore before a class member’s name (e.g., _member
) indicates that it is intended for internal use and should not be accessed directly from outside the class. A double underscore (e.g., __member
) triggers name mangling, making it harder to access the member from outside the class.
class MyClass:
def __init__(self):
self.public = "I am public"
self._protected = "I am protected"
self.__private = "I am private"
def get_private(self):
return self.__private
# Creating an object of MyClass
obj = MyClass()
print(obj.public) # Output: I am public
print(obj._protected) # Output: I am protected
# print(obj.__private) # AttributeError
print(obj.get_private()) # Output: I am private
In this example, public
is accessible from outside the class, _protected
is intended for internal use but can still be accessed directly, and __private
is name-mangled and should be accessed only through a method like get_private()
.
Understanding Python’s naming conventions for access control helps you write code that respects encapsulation while acknowledging Python’s philosophy of trusting the programmer.