Skip to content

Latest commit

 

History

History
1059 lines (738 loc) · 19 KB

11_object_oriented_programming.md

File metadata and controls

1059 lines (738 loc) · 19 KB

Python Object-Oriented Programming (OOP)

Python notes covering object-oriented programming, classes, objects, constructors, the self keyword, inheritance, encapsulation, polymorphism, abstraction, and practical Python programs.

1. What is Object-Oriented Programming?

Definition: Object-Oriented Programming (OOP) is a programming approach based on classes and objects. It helps organize code into reusable and structured components.

OOP helps us:

  • Organize code into classes and objects.
  • Reuse code through inheritance.
  • Protect data using encapsulation.
  • Achieve flexibility using polymorphism.
  • Hide implementation details using abstraction.
  • Build large and maintainable applications.

Python supports object-oriented programming.

2. What is a Class?

Definition: A class is a blueprint or template used to create objects. It defines the properties (attributes) and behaviours (methods) of objects.

Syntax:

class ClassName:
    # Attributes and methods
    pass

Example:

class Student:
    name = "Priya"
    age = 20

    def display(self):
        print(self.name)
        print(self.age)

student = Student()
student.display()

Output:

Priya
20

Here:

  • class is a keyword used to define a class.
  • Student is the class name.
  • name and age are attributes.
  • display() is a method.

3. What is an Object?

Definition: An object is an instance of a class. It represents a real-world entity and contains its own data and behaviour.

Example:

class Student:
    name = "Priya"

student1 = Student()

print(student1.name)

Output:

Priya

Here:

  • Student is a class.
  • student1 is an object.
  • name is an attribute accessed using the object.

Creating Multiple Objects

class Student:
    def display(self):
        print("Welcome to Python")

student1 = Student()
student2 = Student()

student1.display()
student2.display()

Output:

Welcome to Python
Welcome to Python

Multiple objects can be created from the same class.

4. Attributes and Methods

A. Attributes

Definition: Attributes are variables that store the data or properties of an object or class.

Example:

class Student:
    name = "Priya"
    age = 20

student = Student()

print(student.name)
print(student.age)

Output:

Priya
20

B. Methods

Definition: Methods are functions defined inside a class that describe the behaviour of objects.

Example:

class Student:
    def study(self):
        print("Student is studying")

student = Student()
student.study()

Output:

Student is studying

5. The self Keyword

Definition: self represents the current instance of a class. It is used to access the attributes and methods of the current object.

Example:

class Student:
    def display(self):
        print("Hello Student")

student = Student()
student.display()

Output:

Hello Student

Here:

  • self refers to the current object.
  • It allows methods to access instance attributes.
  • It is the first parameter of an instance method.

Example Using self with Attributes

class Student:
    def set_details(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print("Name:", self.name)
        print("Age:", self.age)

student = Student()
student.set_details("Priya", 20)
student.display()

Output:

Name: Priya
Age: 20

6. Constructor in Python

Definition: A constructor is a special method that is automatically called when an object is created. In Python, the __init__() method is commonly used as a constructor to initialize object attributes.

Syntax:

class ClassName:
    def __init__(self):
        # Initialization
        pass

Example:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print("Name:", self.name)
        print("Age:", self.age)

student = Student("Priya", 20)
student.display()

Output:

Name: Priya
Age: 20

Here:

  • __init__() initializes object attributes.
  • self.name stores the student's name.
  • self.age stores the student's age.
  • The constructor is called automatically when the object is created.

Types of Constructors

1. Default Constructor

A constructor that takes only self as its parameter.

class Student:
    def __init__(self):
        print("Student object created")

student = Student()

Output:

Student object created

2. Parameterized Constructor

A constructor that accepts additional parameters to initialize object attributes.

class Student:
    def __init__(self, name):
        self.name = name

student = Student("Priya")

print(student.name)

Output:

Priya

7. Types of Variables in a Class

Python classes commonly use two types of variables.

A. Instance Variables

Definition: Instance variables belong to individual objects. Each object can have different values.

Example:

class Student:
    def __init__(self, name):
        self.name = name

student1 = Student("Priya")
student2 = Student("Amit")

print(student1.name)
print(student2.name)

Output:

Priya
Amit

B. Class Variables

Definition: Class variables are shared by all instances of a class.

Example:

class Student:
    college = "ABC College"

student1 = Student()
student2 = Student()

print(student1.college)
print(student2.college)

Output:

ABC College
ABC College

Difference:

Instance Variable Class Variable
Belongs to an object. Belongs to the class.
Defined using self. Defined directly inside the class.
Each object can have a different value. Shared among objects unless overridden.

8. Inheritance

Definition: Inheritance is an OOP concept in which one class acquires the properties and methods of another class.

The class being inherited from is called the Parent Class or Base Class.

The class that inherits is called the Child Class or Derived Class.

Syntax:

class Parent:
    pass

class Child(Parent):
    pass

Example:

class Animal:
    def eat(self):
        print("Animal is eating")

class Dog(Animal):
    def bark(self):
        print("Dog is barking")

dog = Dog()

dog.eat()
dog.bark()

Output:

Animal is eating
Dog is barking

Here:

  • Animal is the parent class.
  • Dog is the child class.
  • Dog inherits the eat() method from Animal.

Types of Inheritance

1. Single Inheritance

One child class inherits from one parent class.

class Animal:
    def eat(self):
        print("Eating")

class Dog(Animal):
    def bark(self):
        print("Barking")

dog = Dog()
dog.eat()
dog.bark()

2. Multiple Inheritance

One child class inherits from multiple parent classes.

class Father:
    def skills1(self):
        print("Programming")

class Mother:
    def skills2(self):
        print("Drawing")

class Child(Father, Mother):
    pass

child = Child()

child.skills1()
child.skills2()

Output:

Programming
Drawing

3. Multilevel Inheritance

A class inherits from another child class, forming a chain of inheritance.

class Grandparent:
    def show1(self):
        print("Grandparent")

class Parent(Grandparent):
    def show2(self):
        print("Parent")

class Child(Parent):
    def show3(self):
        print("Child")

obj = Child()

obj.show1()
obj.show2()
obj.show3()

Output:

Grandparent
Parent
Child

4. Hierarchical Inheritance

Multiple child classes inherit from the same parent class.

class Animal:
    def eat(self):
        print("Eating")

class Dog(Animal):
    def bark(self):
        print("Barking")

class Cat(Animal):
    def meow(self):
        print("Meowing")

dog = Dog()
cat = Cat()

dog.eat()
dog.bark()

cat.eat()
cat.meow()

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance.

class A:
    def show(self):
        print("Class A")

class B(A):
    pass

class C(A):
    pass

class D(B, C):
    pass

obj = D()
obj.show()

Output:

Class A

9. The super() Function

Definition: The super() function is used to access methods and constructors of a parent class from a child class.

Example:

class Parent:
    def __init__(self):
        print("Parent constructor")

class Child(Parent):
    def __init__(self):
        super().__init__()
        print("Child constructor")

obj = Child()

Output:

Parent constructor
Child constructor

Here, super().__init__() calls the parent class constructor.

10. Encapsulation

Definition: Encapsulation is an OOP concept that combines data and methods into a single unit and controls access to the data.

It helps protect data from direct and unintended modification.

Access Modifiers in Python

Python commonly uses naming conventions to indicate three levels of access.

Type Syntax Description
Public name Accessible from anywhere.
Protected _name Intended for use within a class and its subclasses.
Private __name Name-mangled to discourage direct access.

Example:

class Student:
    def __init__(self):
        self.name = "Priya"
        self._age = 20
        self.__marks = 90

    def display(self):
        print("Name:", self.name)
        print("Age:", self._age)
        print("Marks:", self.__marks)

student = Student()
student.display()

Output:

Name: Priya
Age: 20
Marks: 90

Here:

  • name is public.
  • _age is protected by convention.
  • __marks is private through name mangling.

Accessing Private Variables Using a Method

class Student:
    def __init__(self):
        self.__marks = 90

    def get_marks(self):
        return self.__marks

student = Student()

print(student.get_marks())

Output:

90

11. Polymorphism

Definition: Polymorphism means one interface or method name can have different behaviours depending on the object or context.

It allows different classes to use the same method name with different implementations.

A. Method Overriding

Definition: Method overriding occurs when a child class provides its own implementation of a method already defined in its parent class.

Example:

class Animal:
    def sound(self):
        print("Animal makes a sound")

class Dog(Animal):
    def sound(self):
        print("Dog barks")

class Cat(Animal):
    def sound(self):
        print("Cat meows")

dog = Dog()
cat = Cat()

dog.sound()
cat.sound()

Output:

Dog barks
Cat meows

B. Method Overloading

Definition: Method overloading means defining multiple methods with the same name but different parameters.

Python does not support traditional method overloading based on parameter signatures. Similar behaviour can be achieved using default arguments or variable-length arguments.

Example Using Default Arguments:

class Calculator:
    def add(self, a, b, c=0):
        return a + b + c

calc = Calculator()

print(calc.add(10, 20))
print(calc.add(10, 20, 30))

Output:

30
60

C. Operator Overloading

Definition: Operator overloading allows operators to behave differently for user-defined objects using special methods.

Example:

class Number:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.value + other.value

num1 = Number(10)
num2 = Number(20)

print(num1 + num2)

Output:

30

Here, __add__() defines the behaviour of the + operator for objects of the Number class.

12. Abstraction

Definition: Abstraction is an OOP concept that hides internal implementation details and shows only the essential features to the user.

Python supports abstraction using the abc module.

Example:

from abc import ABC, abstractmethod

class Animal(ABC):

    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        print("Dog barks")

dog = Dog()
dog.sound()

Output:

Dog barks

Here:

  • ABC is used to create an abstract base class.
  • @abstractmethod defines a method that subclasses must implement.
  • Dog provides the implementation of sound().

Important: An abstract class containing unimplemented abstract methods cannot be instantiated directly.

13. Difference Between the Four Main OOP Principles

Principle Meaning
Inheritance Reusing properties and methods from another class.
Encapsulation Combining data and methods and controlling access to data.
Polymorphism One interface with different behaviours.
Abstraction Hiding implementation details and showing essential features.

14. Static Methods and Class Methods

A. Static Method

Definition: A static method belongs to a class and does not require access to instance or class-specific data.

It is defined using the @staticmethod decorator.

Example:

class Calculator:

    @staticmethod
    def add(a, b):
        return a + b

print(Calculator.add(10, 20))

Output:

30

B. Class Method

Definition: A class method works with class-level data and receives the class itself as its first parameter, conventionally named cls.

It is defined using the @classmethod decorator.

Example:

class Student:
    college = "ABC College"

    @classmethod
    def display(cls):
        print(cls.college)

Student.display()

Output:

ABC College

Difference:

Static Method Class Method
Uses @staticmethod. Uses @classmethod.
Does not receive an automatic first argument. Receives cls automatically.
Does not automatically access class or instance data. Can access class variables through cls.

15. Practical Python Programs Using OOP

Program 1: Create a Student Class

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print("Name:", self.name)
        print("Age:", self.age)

student = Student("Priya", 20)
student.display()

Output:

Name: Priya
Age: 20

Program 2: Create a Calculator Class

class Calculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        return a / b

calc = Calculator()

print("Addition:", calc.add(10, 5))
print("Subtraction:", calc.subtract(10, 5))
print("Multiplication:", calc.multiply(10, 5))
print("Division:", calc.divide(10, 5))

Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

Program 3: Demonstrate Single Inheritance

class Person:
    def display_name(self):
        print("Name: Priya")

class Student(Person):
    def display_course(self):
        print("Course: BCA")

student = Student()

student.display_name()
student.display_course()

Output:

Name: Priya
Course: BCA

Program 4: Demonstrate Method Overriding

class Parent:
    def show(self):
        print("This is the parent class")

class Child(Parent):
    def show(self):
        print("This is the child class")

obj = Child()
obj.show()

Output:

This is the child class

Program 5: Demonstrate Encapsulation

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def display_balance(self):
        print("Balance:", self.__balance)

account = BankAccount(1000)

account.deposit(500)
account.display_balance()

Output:

Balance: 1500

Program 6: Demonstrate Polymorphism

class Bird:
    def sound(self):
        print("Bird makes a sound")

class Parrot:
    def sound(self):
        print("Parrot talks")

class Crow:
    def sound(self):
        print("Crow caws")

for animal in [Bird(), Parrot(), Crow()]:
    animal.sound()

Output:

Bird makes a sound
Parrot talks
Crow caws

Program 7: Demonstrate Abstraction

from abc import ABC, abstractmethod

class Shape(ABC):

    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def area(self):
        return self.length * self.breadth

rectangle = Rectangle(10, 5)

print("Area:", rectangle.area())

Output:

Area: 50

16. Practice Questions

Try solving these programs yourself:

  1. Create a Student class with name, age, and course attributes.
  2. Create an object of a class and display its attributes.
  3. Create a class with a method to calculate the area of a rectangle.
  4. Write a program using a constructor to initialize student details.
  5. Demonstrate the use of the self keyword.
  6. Create a class with both class variables and instance variables.
  7. Demonstrate single inheritance using a parent and child class.
  8. Write a program to demonstrate multiple inheritance.
  9. Demonstrate multilevel inheritance using three classes.
  10. Write a program using the super() function.
  11. Demonstrate encapsulation using a private variable.
  12. Write a program to demonstrate method overriding.
  13. Demonstrate polymorphism using different classes with the same method name.
  14. Create an abstract class using the abc module.
  15. Write a program demonstrating a static method.
  16. Write a program demonstrating a class method.
  17. Create a calculator class using different methods.
  18. Demonstrate operator overloading using the __add__() method.

17. Key Points to Remember

  • OOP stands for Object-Oriented Programming.
  • A class is a blueprint for creating objects.
  • An object is an instance of a class.
  • Attributes store data inside a class or object.
  • Methods define the behaviour of objects.
  • self refers to the current instance.
  • __init__() initializes object attributes.
  • Instance variables belong to individual objects.
  • Class variables are shared among instances.
  • Inheritance allows one class to acquire features from another.
  • super() accesses parent class methods.
  • Encapsulation combines data and methods and controls access.
  • Polymorphism allows different behaviours through a common interface.
  • Method overriding provides a child-specific implementation.
  • Python does not support traditional signature-based method overloading.
  • Abstraction hides implementation details.
  • ABC and @abstractmethod support abstraction.
  • @staticmethod defines a static method.
  • @classmethod defines a class method.
  • OOP helps create reusable, organized, and maintainable programs.

End of Python Object-Oriented Programming Notes