0% completed
Access modifiers are key concepts in object-oriented programming that control the visibility of class members(attributes and methods). Python's approach to access modifiers is unique because it does not have explicit keywords like private
, protected
, or public
found in some other languages. Instead, Python uses naming conventions to indicate the intended level of access for class members.
Public attributes are accessible from anywhere, both inside and outside of the class. In Python, any attribute without a leading underscore is considered public by default.
In this example, we create a Car
class with public attributes to demonstrate how they can be accessed freely within and outside of the class.
Explanation:
self.make
and self.model
are declared without any underscores, making them public.my_car = Car("Toyota", "Corolla")
: Instantiates the Car
class.make
and model
.Private attributes are intended to be hidden from outside class access. In Python, you denote private attributes by prefixing the name with two underscores (__
), which also enables name mangling to further protect these attributes from external access.
In this example, we demonstrate defining private attributes in the Car
class and accessing them through a class method.
Explanation:
self.__make
and self.__model
are private due to the double underscore prefix.display_info()
is a method that safely accesses these private attributes within the class.my_car.__make
) would result in an error due to Python’s name mangling.Protected attributes are meant to be accessed within the class and subclasses but should be considered private from an outside perspective. They are indicated by a single underscore (_
) prefix.
In this example, the Vehicle
class demonstrates protected attributes accessed by a subclass.
Explanation:
self._type
in the Vehicle
class is a protected attribute indicated by a single underscore.Car
class, which inherits from Vehicle
, can access this protected attribute in its display
method to show how subclasses can interact with protected members.This comprehensive look at Python's access modifiers, demonstrated through practical examples, highlights how Python relies on conventions to indicate the intended level of accessibility for class attributes. These conventions help maintain a clean and understandable codebase, especially in large projects or frameworks.
.....
.....
.....