Wednesday, 6 November 2024

Global ,protected and private attributes in Python.

 what are global,  protected and private attributes in python?

 Global variable :In Python, a global variable is one that can be accessed across different functions within the same module. To define and use a global variable, you simply declare it outside of any function. If you need to modify a global variable inside a function, you should use the global keyword to let Python know that you're referring to the global scope.


# Define a global variable

count = 0


def increment():

    global count  # Declare that we want to use the global 'count'

    count += 1


def print_count():

    print("Count:", count)


# Usage

increment()

print_count()  # Output: Count: 1

increment()

print_count()  # Output: Count: 2


In this example:

  • count is a global variable.
  • Inside increment(), the global keyword tells Python that we’re referring to the global count variable rather than creating a new local one.
  • This allows us to update count globally from within the function.


Protected variable : In Python, protected attributes are typically used to indicate that an attribute should not be accessed directly outside of its class or subclass. Although Python doesn't enforce strict access control like some other languages, by convention, a single underscore (_) at the beginning of a variable name is used to indicate that it is intended for internal use within the class and its subclasses. This is a weak form of "protection."


class Person:

    def __init__(self, name, age):

        self.name = name          # Public attribute

        self._age = age           # Protected attribute (by convention)


    def get_age(self):

        return self._age


class Employee(Person):

    def __init__(self, name, age, employee_id):

        super().__init__(name, age)

        self.employee_id = employee_id


    def display_info(self):

        # Accessing protected attribute from the parent class

        print(f"Name: {self.name}, Age: {self._age}, Employee ID: {self.employee_id}")


# Usage

emp = Employee("Alice", 30, "E123")

emp.display_info()          # Output: Name: Alice, Age: 30, Employee ID: E123

print(emp._age)             # Accessing protected attribute outside the class (not recommended)



Private attribute: In Python, private attributes are indicated by prefixing the attribute name with a double underscore (__). This makes the attribute name "name-mangled" to limit direct access from outside the class. Name mangling changes the attribute name to include the class name as a prefix, making it harder (but not impossible) to access it from outside the class.

class Person:
    def __init__(self, name, age):
        self.name = name            # Public attribute
        self.__age = age            # Private attribute (name mangled)

    def get_age(self):
        return self.__age           # Method to access the private attribute

# Usage
person = Person("Alice", 30)

print(person.name)         # This works (public attribute)
print(person.get_age())    # This works (accessing private attribute via method)

# Attempting to access the private attribute directly will raise an AttributeError
# print(person.__age)      # This will cause an error

# However, name mangling means it can still be accessed like this:
print(person._Person__age) # Not recommended, but possible (Output: 30)



No comments:

Post a Comment