Encapsulation-Abstraction - Tagged
Introduction to Python
Topic: Encapsulation and Abstraction
Instructor: Dr. Ali Sadiq
Learning Outcomes
Understand Encapsulation
Principles of Encapsulation
Importance of Encapsulation
Understand Abstraction
Examples of Abstraction in daily life
Importance in Object-Oriented Programming
Access modifiers in Python (Public, Private, Protected)
Working with public and non-public attributes
Name mangling concept
Getters and Setters in Python
Defining Getters and Setters in classes
Using Python @property decorator
Implementation of @property decorator
Encapsulation
Definition
Encapsulation is a fundamental OOP feature.
Bundles data members and methods into a single unit (class).
Importance
Aids in data hiding by organizing data and methods logically.
Users care about input/output, not internal workings.
Objects function independently, preventing unauthorized access to data.
Benefits
Well-defined, readable code
Prevents accidental changes
Enhances security
Promotes code reusability
Abstraction
Concept
Encapsulation implements Abstraction.
Hides the complexity of class implementation from the user.
Users understand what functionality does but not how it works.
Access Modifiers in Python
Access Levels:
Public: Accessible everywhere
Protected: Accessible within class and subclass
Private: Accessible only within the class
Achieved using underscores: single for protected, double for private.
Example:
Access specifiers:
Private: Yes (own class), No (derived class or object)
Protected: Yes (own and derived classes), No (from object)
Public: Yes (all classes)
Getters and Setters
Purpose
Ensure data encapsulation by controlling access/modification of private attributes.
Getter Method
Retrieves the value of a private attribute.
Named typically with a prefix 'get_'.
Example:
get_name()retrieves name attribute.
Setter Method
Modifies the private attribute's value.
Named typically with a prefix 'set_'.
Example:
set_age()modifies the age attribute.
@property Decorator
Functionality
Simplifiesgetter/setter functionality in OOP.
Provides a way to control access, modification, and deletion of attributes.
Usage
Defined with
@propertyfor getter and@<property>.setterfor setter.
Examples
Without Getters and Setters
A class can lead to uncontrolled access to attribute values.
With Getters and Setters
Provides a controlled access mechanism with validation.
Conclusion
Encapsulation and abstraction are essential in ensuring secure, maintainable, and reusable code in Object-Oriented Programming.