Python notes covering object-oriented programming, classes, objects, constructors, the self keyword, inheritance, encapsulation, polymorphism, abstraction, and practical Python programs.
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.
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
passExample:
class Student:
name = "Priya"
age = 20
def display(self):
print(self.name)
print(self.age)
student = Student()
student.display()Output:
Priya
20
Here:
classis a keyword used to define a class.Studentis the class name.nameandageare attributes.display()is a method.
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:
Studentis a class.student1is an object.nameis an attribute accessed using the object.
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.
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
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
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:
selfrefers to the current object.- It allows methods to access instance attributes.
- It is the first parameter of an instance method.
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
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
passExample:
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.namestores the student's name.self.agestores the student's age.- The constructor is called automatically when the object is created.
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
Python classes commonly use two types of 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
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. |
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):
passclass 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:
Animalis the parent class.Dogis the child class.Doginherits theeat()method fromAnimal.
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
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.
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.
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. |
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:
nameis public._ageis protected by convention.__marksis private through name mangling.
class Student:
def __init__(self):
self.__marks = 90
def get_marks(self):
return self.__marks
student = Student()
print(student.get_marks())Output:
90
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.
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
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
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.
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:
ABCis used to create an abstract base class.@abstractmethoddefines a method that subclasses must implement.Dogprovides the implementation ofsound().
Important: An abstract class containing unimplemented abstract methods cannot be instantiated directly.
| 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. |
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
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. |
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
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
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
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
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
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
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
Try solving these programs yourself:
- Create a
Studentclass with name, age, and course attributes. - Create an object of a class and display its attributes.
- Create a class with a method to calculate the area of a rectangle.
- Write a program using a constructor to initialize student details.
- Demonstrate the use of the
selfkeyword. - Create a class with both class variables and instance variables.
- Demonstrate single inheritance using a parent and child class.
- Write a program to demonstrate multiple inheritance.
- Demonstrate multilevel inheritance using three classes.
- Write a program using the
super()function. - Demonstrate encapsulation using a private variable.
- Write a program to demonstrate method overriding.
- Demonstrate polymorphism using different classes with the same method name.
- Create an abstract class using the
abcmodule. - Write a program demonstrating a static method.
- Write a program demonstrating a class method.
- Create a calculator class using different methods.
- Demonstrate operator overloading using the
__add__()method.
- 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.
selfrefers 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.
ABCand@abstractmethodsupport abstraction.@staticmethoddefines a static method.@classmethoddefines a class method.- OOP helps create reusable, organized, and maintainable programs.
End of Python Object-Oriented Programming Notes