Introduction to Object-Oriented Programming in Python

Jul 8, 2024

Introduction to Object-Oriented Programming in Python

Language Fundamentals Recap

  • Variables and functions: How to define and use them.
  • Modules: Understanding how to work with different files.

Moving to Concepts

Object-Oriented Programming (OOP)

  • Famous for Python: Python supports various programming paradigms including functional and object-oriented programming.
  • Why Use Objects?: Objects represent real-world entities with attributes (data) and behaviors (methods).

Understanding Objects

  • Real-World Analogy: Everything in the real world has attributes and behaviors.
  • Attributes and Behaviors: For example, a 'Person' object has attributes like height, age, and behaviors like walking, talking.
  • Variables as Attributes: Used to store data in an object.
  • Methods as Behaviors: Functions inside an object, referred to as methods.
  • Thinking in Objects: Essential for tackling complex problems by visualizing them as objects interacting with each other.

Core OOP Concepts

Class and Object

  • Class: The blueprint for creating objects (instances). Contains attributes and methods.
  • Object: An instance of a class. Contains actual data.
  • Examples: Computer class with attributes CPU, RAM, and methods like config.

Constructors

  • init Method: Special method to initialize an object’s state. Automatically called when an object is created.
  • Attributes Initialization: How to use the init method to initialize object attributes.

Encapsulation

  • Definition: Combining variables and functions into a single entity (class), hiding the complex implementation details.
  • Importance: Ensures data integrity and hiding the internal state of objects from the outside world.

Inheritance

  • Single Inheritance: One class inherits properties from another class.
    • class B(A): Class B inherits from Class A.
  • Multi-Level Inheritance: A class E inherits from another class D which inherits from class C.
  • Multiple Inheritance: A class inherits from more than one base class.
    • class C(A, B): Class C inherits from classes A and B.

Polymorphism

  • Definition: One interface, multiple implementations.
  • Forms of Polymorphism:
    • Duck Typing: “If it looks like a duck and quacks like a duck, it’s a duck.”
      • Example: Different classes with the same execute method can be used interchangeably in a context that requires the execute method.
    • Operator Overloading: Giving new meaning to the operators (e.g., +, -).
      • Example: Overloading the + operator to add two objects.
    • Method Overloading: Not directly supported in Python; can achieve similar functionality using default arguments.
    • Method Overriding: Redefining a method in the derived class that is already defined in the base class.

Practical Examples and Use Cases

Creating Classes and Objects in Python

  • Example: Define the Computer class with attributes and methods.
class Computer:
    def __init__(self, cpu, ram):
        self.cpu = cpu
        self.ram = ram

    def config(self):
        print(f'Config is {self.cpu}, {self.ram}')

comp1 = Computer('i5', '16GB')
comp1.config()

Inheritance in Depth

  • Example: Single Inheritance
class A:
    def feature1(self):
        print('Feature 1 working')

class B(A):
    def feature2(self):
        print('Feature 2 working')
  • Example: Multi-Level Inheritance
class C(B):
    def feature3(self):
        print('Feature 3 working')
  • Example: Multiple Inheritance
class D:
    def feature4(self):
        print('Feature 4 working')

class E(A, D):
    pass

Method Resolution Order (MRO)

  • Rule: Left to right in case of multiple inheritance.
  • super() Method: To call the parent class method.

Polymorphism Detailed

Duck Typing

class Pycharm:
    def execute(self):
        print('Compiling')
        print('Running')

class MyEditor:
    def execute(self):
        print('Spell Check')
        print('Compiling')
        print('Running')
  • Example usage in another class
class Laptop:
    def code(self, ide):
        ide.execute()

ide = Pycharm()
lap1 = Laptop()
lap1.code(ide)

Operator Overloading

class Student:
    def __init__(self, m1, m2):
        self.m1 = m1
        self.m2 = m2

    def __add__(self, other):
        m1 = self.m1 + other.m1
        m2 = self.m2 + other.m2
        return Student(m1, m2)

s1 = Student(58, 69)
s2 = Student(60, 65)
s3 = s1 + s2  # Calls __add__

Method Overriding Example

class A:
    def show(self):
        print('in A show')

class B(A):
    def show(self):
        print('in B show')
class Computer:
  def __init__(self,cpu,ram):
    self.cpu = cpu
    self.ram = ram

  def config(self):
    print(f"Config is: {self.cpu}, {self.ram}")

comp1 = Computer('i5','16GB')
comp1.config()

Summary

  • OOP is a crucial paradigm in Python, allowing for efficient and organized code through objects and classes.
  • Core concepts include Classes, Objects, Inheritance, Encapsulation, and Polymorphism.
  • Python’s flexibility with OOP makes it powerful for solving real-world problems through modeling them as interacting objects.