In object-oriented programming (OOP) in Python, classes and objects play a crucial role. Classes are like a blueprint or blueprint that defines what an object should contain, while objects are instances of a class, which contains variables and methods defined by the class. In this chapter, we're going to delve into an important aspect of OOP in Python - Encapsulation and access modifiers.
7.3.1 Encapsulation
Encapsulation is one of the four fundamental concepts of object-oriented programming. It refers to the grouping of data and the methods that manipulate that data within a single unit, which is the class. In other words, encapsulation is a way to protect data from being accessed directly.
In Python, encapsulation is accomplished using private and protected methods and variables. A private variable is preceded by two underscores (__), while a protected variable is preceded by a single underscore (_). Here is an example of how encapsulation is implemented in Python:
class Car: def __init__(self): self.__price = 20000 def sell(self): print("Selling price: ", self.__price) car = Car() car.sell()
In this example, the __price variable is private, so it cannot be accessed directly from outside the class. Instead, it is accessed through the sell() method.
7.3.2 Access Modifiers
Access modifiers are used in OOP to define the scope of a variable, method, or class. In Python, there are three types of access modifiers - public, private, and protected.
Public members (variables, methods, etc.) are accessible from any part of the program. All members of a class are public by default in Python.
Private members are accessible only within their own class. They are defined by adding two underscores before the member name.
Protected members are similar to private members, but they are accessible within the class and its subclasses. They are defined by adding a single underscore before the member name.
class Car: def __init__(self): self._speed = 60 # protected member self.__price = 20000 # private member
In this example, _speed is a protected member and __price is a private member.
In Python, access modifiers are more of a convention than a hard and fast rule. It is still possible to access private and protected members directly, although this is considered bad practice.
To conclude, encapsulation and access modifiers are powerful tools in OOP that help maintain data integrity and make code more secure and maintainable. They are an essential part of building robust and efficient systems with Python and Django.
We hope this chapter has given you a clear understanding of encapsulation and access modifiers in Python. In the next chapter, we'll explore more advanced concepts of OOP in Python.