Chapter 6: Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects. Objects encapsulate data (attributes) and behavior (methods), making it easier to manage and scale programs.

Key Concepts of OOP

  1. Classes and Objects:

    • A class is a blueprint for creating objects.

    • An object is an instance of a class.

  2. Attributes and Methods:

    • Attributes represent the data of an object.

    • Methods are functions defined inside a class that operate on objects.

  3. Encapsulation:

    • Bundling data and methods together.

    • Restricting access to certain parts of an object using access modifiers.

  4. Inheritance:

    • Mechanism for creating a new class (child) from an existing class (parent).

  5. Polymorphism:

    • Ability for methods to perform different actions based on the object that calls them.

  6. Abstraction:

    • Hiding complex implementation details and showing only the essential features.

Defining and Creating Classes

Syntax:

Example:

Attributes and Methods

Instance Attributes:

  • Specific to an object.

  • Defined in the __init__ method using self.

Class Attributes:

  • Shared by all instances of the class.

  • Defined directly within the class.

Encapsulation

Encapsulation allows control over access to attributes and methods.

Access Modifiers:

  • Public: Attributes and methods accessible anywhere (default).

  • Protected: Indicated by a single underscore _. Should be accessed only within the class and its subclasses.

  • Private: Indicated by a double underscore __. Accessible only within the class.

Inheritance

Inheritance enables a class to acquire attributes and methods from another class.

Syntax:

Example:

Polymorphism

Polymorphism allows different classes to define methods with the same name but different behavior.

Example:

Abstraction

Abstraction hides the implementation details and shows only the functionality.

Example with Abstract Base Class:

Exercises

Exercise 1:

Create a class Car with attributes make, model, and year. Include a method to display the car’s details.

Solution:

Exercise 2:

Create a base class Employee and a subclass Manager. The Manager class should have an additional attribute department and a method to display all details.

Solution:

Exercise 3:

Create an abstract class Appliance with a method turn_on. Implement two subclasses WashingMachine and Refrigerator that provide specific implementations for turn_on.

Solution:

In the next chapter, we will explore modules and packages, understanding how to organize and reuse code effectively in Python.

Last updated