Python in Acess modifier

 1. Public Members:

class MyClass:

    def __init__(self, x):

        self.public_attribute = x  # Public attribute

    def public_method(self):

        print("This is a public method.")

# Accessing public members

obj = MyClass(10)

print(obj.public_attribute) 

obj.public_method()        


2. Protected Members

Convention: Attributes and methods with a single underscore prefix (_) are considered protected.


class MyClass:

    def __init__(self, x):

        self._protected_attribute = x  # Protected attribute

    def _protected_method(self):

        print("This is a protected method.")

# Accessing protected members (discouraged)

obj = MyClass(10)

print(obj._protected_attribute)  # Accessing protected attribute (discouraged)

obj._protected_method()        # Calling protected method (discouraged)



3. Private Members

Convention: Attributes and methods with a double underscore prefix (__) are considered private.

class MyClass:

    def __init__(self, x):

        self.__private_attribute = x  # Private attribute

    def __private_method(self):

        print("This is a private method.")

# Accessing private members (using name mangling)

obj = MyClass(10)

# print(obj.__private_attribute)  # Direct access won't work (AttributeError)

print(obj._MyClass__private_attribute)  # Accessing mangled name

# obj.__private_method()  # Direct access won't work (AttributeError)

Comments

Popular posts from this blog

ch 2 pm

pm unit :1

ch 3 pm