How does Python handle access modifiers for class members (attributes and methods)?

How does Python handle access modifiers for class members (attributes and methods)?

a) Python uses naming conventions like single and double underscores to indicate the intended access level
b) Python uses keywords like private and protected to define access modifiers
c) Python does not support any form of access control for class members
d) Python uses decorators to control access to class members

Answer:

a) Python uses naming conventions like single and double underscores to indicate the intended access level

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top