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()
, theglobal
keyword tells Python that we’re referring to the globalcount
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)
__
). 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.