Encapsulation-Abstraction - Tagged

Introduction to Python

  • Topic: Encapsulation and Abstraction

  • Instructor: Dr. Ali Sadiq

Learning Outcomes

  1. Understand Encapsulation

  2. Principles of Encapsulation

  3. Importance of Encapsulation

  4. Understand Abstraction

  5. Examples of Abstraction in daily life

  6. Importance in Object-Oriented Programming

  7. Access modifiers in Python (Public, Private, Protected)

  8. Working with public and non-public attributes

  9. Name mangling concept

  10. Getters and Setters in Python

  11. Defining Getters and Setters in classes

  12. Using Python @property decorator

  13. 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 @property for getter and @<property>.setter for 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.