Python - Inheritance
In Python, attributes in a class can have different access levels: public, protected, and private. These access levels are indicated by naming conventions, and they provide a way to control the visibility and use of attributes in inheritance scenarios.
Let's consider an example to illustrate the differences between public, protected, and private attributes in inheritance:
class Animal:
# Public attribute
legs = 4
def __init__(self, name):
# Protected attribute
self._name = name
def display_info(self):
return f"{self._name} has {self.legs} legs"
# Inherit from the Animal class
class Dog(Animal):
def __init__(self, name, breed):
# Call the constructor of the base class using super()
super().__init__(name)
# Private attribute
self.__breed = breed
def display_dog_info(self):
return f"{self._name} is a {self.__breed} dog"
# Create instances of the derived class
dog_instance = Dog(name="Buddy", breed="Golden Retriever")
# Access public and protected attributes
legs_count = dog_instance.legs
name_attr = dog_instance._name
# Access private attribute using name mangling (not recommended)
breed_attr = dog_instance._Dog__breed
# Display information using methods
animal_info = dog_instance.display_info()
dog_info = dog_instance.display_dog_info()
print(legs_count) # Output: 4
print(name_attr) # Output: Buddy
print(breed_attr) # Output: Golden Retriever (using name mangling)
print(animal_info) # Output: Buddy has 4 legs
print(dog_info) # Output: Buddy is a Golden Retriever dog
In this example, the Animal
class has a public attribute legs
and a protected attribute _name
. The Dog
class inherits from Animal
and introduces a private attribute __breed
. The program demonstrates how these attributes can be accessed in inheritance scenarios.
While Python does not enforce strict access control, the naming conventions are used to indicate the intended use of attributes. Public attributes are accessible from outside the class, protected attributes are intended for internal use, and private attributes (using name mangling) are not recommended to be accessed directly from outside the class.
Output:
4 Buddy Golden Retriever Buddy has 4 legs Buddy is a Golden Retriever dog