CHAPTER22
CHAPTER22
• There are some functions in Python which are compatible to run with
multiple data types.
• One such function is the len() function. It can run with many data types in
Python. Let's look at some example use cases of the function.
• Examples Polymorphic len() function
print(len("Devincept"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
• Output: 9 3 2 Here, we can see that many data types such as string, list,
tuple, set, and dictionary can work with the len() function. However, we can
see that it returns specific information about specific data types.
Encapsulation in Python
• Encapsulation is also an essential aspect of object-oriented
programming.
• It is used to restrict access to methods and variables.
• In encapsulation, code and data are wrapped together within a single
unit from being modified by accident.
• This puts restrictions on accessing variables and methods directly
and can prevent the accidental modification of data.
• To prevent accidental change, an object’s variable can only be
changed by an object’s method.
• Those types of variables are known as private variable.
• A class is an example of encapsulation as it encapsulates all the data
that is member functions, variables, etc.
Key Concepts
1.Data Hiding: Protecting the internal state of an object from
unintended modification by restricting access to certain components.
2.Access Modifiers: Keywords that set the visibility of class members
(attributes and methods).
Access Modifiers
•Python does not have explicit keywords for private, protected, or public access
modifiers. Instead, it uses naming conventions:
•Public: Accessible from outside the class. (No leading underscore)
•Protected: Intended to be accessed by subclasses. (Single leading underscore,
e.g., _attribute)
•Private: Intended to be hidden from outside the class. (Double leading
underscore, e.g., __attribute)
Protected Access Modifier
class ElectricCar(Car):
def __init__(self, make, model, battery):
super().__init__(make, model)
self.battery = battery
def display_info(self):
print(f"Make: {self._make}, Model: {self._model}, Battery: {self.battery}")