Object oriented programming in
python
Chapter 5
Object oriented Programming
• Overview of OOP (Object Oriented Programming):
• a. Class: A user-defined prototype for an object that defines a set of attributes
that characterize any object of the class. The attributes are data members
(class variables and instance variables) and methods, accessed via dot
notation.
• b. Class variable: A variable that is shared by all instances of a class. Class
variables are defined within a class but outside any of the class's methods.
Class variables are not used as frequently as instance variables are.
• c. Data member: A class variable or instance variable that holds data
associated with a class and its objects.
• d. Function overloading: The assignment of more than one behavior to a
particular function. The operation performed varies by the types of objects or
arguments involved.
• e. Instance variable: A variable that is defined inside a method and belongs
only to the current instance of a class.
• f. Inheritance: The transfer of the characteristics of a class to other classes
that are derived from it.
• g. Instance: An individual object of a certain class. An object obj that belongs
to a class Circle, for example, is an instance of the class Circle.
• h. Instantiation: The creation of an instance of a class.
• i. Method : A special kind of function that is defined in a class definition.
• j. Object: A unique instance of a data structure that is defined by its class. An
object comprises both data members (class variables and instance variables)
and methods.
• k. Operator overloading: The assignment of more than one function to a
particular operator.
Class
• Defining a Class:
➢ class should be defined using class keyword.
• Syntax:
class classname():
‘’’Documentation String/ comments for understanding ‘’’
variable: (instance, static and local variables)
methods: (instance, static and class methods)
• Ex:1
class myclass():
'''this section is for comments'''
a,b=20,30
print(a+b)
Ex:2
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
OOPs - Self
➢ Self is a python provided implicit variable always pointing to current
object.
➢ Self is used to access object related variables (instance vaiables) and
object related methods (instance methods)
➢ Python is responsible for assigning the value for self
➢ In a constructor the first argument should always be self
Ex:
class myclass():
def init (self, name, age, address, workplace):
➢ self should be first parameter inside instance methods
➢ Instance attributes are those attributes that are not shared by objects.
Every object has its own copy of the instance attribute.
def talk(self):
➢ It is not mandatory to use self to represent current object in python, we
can use any name
class myclass():
'''this is my first program in oops'''
def init (self,name,age,address,workplace):
self.name=name
self.age=age
Output:
self.address=address
self.workplace=workplace
hello, i am: anand
my age is: 30
def details(self): i live in: Akurdi
print("hello, i am: ", self.name) i work at: PCP
print("my age is: ", self.age) 30
print("i live in: ", self.address)
print("i work at: ", self.workplace)
t=myclass("anand",30,"Akurdi", "PCP")
t.details()
print(t.age)
Ex:
class myclass():
'''this is my first program in oops'''
def init (angel,name,age,address,workplace):
angel.name=name Output:
angel.age=age ------------
angel.address=address hello, i am: anand
angel.workplace=workplace my age is: 30
i live in: Warje
def details(angel): i work at: Advanto Software Pvt Ltd
print("hello, i am: ", angel.name)
print("my age is: ", angel.age) print("i hello, i am: Hai
live in: ", angel.address) print("i work my age is: 40
at: ", angel.workplace) i live in: Warje
i work at: Advanto Software Pvt Ltd
t=myclass("anand",30,"Warje", "Advanto Software Pvt Ltd")
t.details()
t1=myclass("Hai",40,"Warje", "Advanto Software Pvt Ltd")
t1.details()
OOPs - Object
◊ Physical existence of a class is nothing but object. We can create any
number of objects for a class.
Syntax: reference_variable = class_name()
Ex:
class myadd():
def init (self):
pass
def addition(self):
a=10
b=20
print(a+b)
ad=myadd() Object
ad.addition()
OOPs - Constructor
◊ A special method available in python which is used to initialize
(Assign values) the instance members of the class
◊ Constructor is executed automatically when we create the object of
this class.
Syntax for declaring a constructor:
def init (self):
# body of the constructor
➢ The name of the constructor must be init
➢ The constructor should have at least one argument i.e (self)
➢ Constructor is optional and if we don’t provide any constructor then
python will provide a default constructor.
OOPs - Constructor
➢ Constructor will be executed only once per object
Ex:
class myadd():
def init (self):
print("testing constructor")
def addition(self):
a=10
b=20
print(a+b) Output:
------------
t1=myadd() testing constructor
t2=myadd() testing constructor
t3=myadd() testing constructor
t4=myadd() testing constructor
t1.addition() 30
OOPs - Example
➢ We can pass multiple objects into single reference variable
class Test:
def init (self,name,age,status):
Output:
self.name=name
------------
self.age=age
self.status=status name: anand
age: 30
def details(self): status: single
print("name: ", self.name)
name: raghu
print(“age: ", self.age)
age: 29
print(“status: ", self.status) status: married
print()
t=[Test('anand', 30,'single'),Test("raghu", 29, "married")]
for i in t:
i.details()
OOPs – Class Methods
◊ Program to print number of objects created in a class
class c1:
# this is used to print the number
# of instances of a class
counter = 0
# constructor of geeks class
def __init__(self):
# increment
geeks.counter += 1
# object or instance of geeks class
g1 = c1()
g2 = c1()
g3 = c1()
# Number of objects created are: 3
print(c1.counter)
Public Access modifier
➢ By default the member variables and methods are public which means
they can be accessed from anywhere outside or inside the class.
➢ No public keyword is required to make the class public.
➢ class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age) o\p:Name: John
Age: 20
s = Student("John", 20)
s.display()
Private Access Modifier
• Class properties and methods with private access modifier
can only be accessed within the class where they are defined
and cannot be accessed outside the class.
• In Python private properties and methods are declared by
adding a prefix with two underscores(‘__’) before their
declaration.
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number
self.__balance = balance
def __display_balance(self):
print("Balance:", self.__balance)
b = BankAccount(1234567890, 5000)
b.__display_balance()
o/p:AttributeError: 'BankAccount' object has no attribute
'__display_balance'
Method overloading
• Method overloading refers to defining
multiple methods with the same name but
with different parameter types or the number
of parameters.
• In Python, method overloading is achieved
using default arguments.
class MyClass:
def my_method(self, arg1, arg2=None):
if arg2:
print(arg1 + arg2)
else:
print(arg1)
# Calling the method with one argument
obj = MyClass()
obj.my_method(10)
# Calling the method with two arguments
obj.my_method(10, 20)
o\p:10
30
Inheritance
• It is used to inherit the properties and behaviours of one class
to another.
• The class that inherits another class is called a child class and
the class that gets inherited is called a base class or parent
class.
• Types:
1.Single Inheritance
2.Multiple Inheritance
3.Multilevel Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance
• Creating a Parent Class
class ParentClassName:
{class body}
• Creating a Child Class
class SubClassName (ParentClass1, ParentClass2, ...):
{sub class body}
1.Single Inheritance
class Parent:
def parentMethod(self):
print ("Calling parent method")
class Child(Parent):
def childMethod(self):
print ("Calling child method")
c = Child()
c.childMethod()
c.parentMethod()
Multiple Inheritance
class Father:
def skills(self):
print("Gardening, Carpentry")
class Mother:
def skills(self):
print("Cooking, Art")
class Child(Father, Mother):
def skills(self):
Father.skills(self) # Call Father's skills
Mother.skills(self) # Call Mother's skills
print("Programming, Music")
# Usage
child = Child()
child.skills()
# Output:
Gardening, Carpentry
Cooking, Art
Programming, Music
3.Multilevel Inheritance
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
# invoking constructor of Grandfather class
Grandfather.__init__(self, grandfathername)
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname
Father.__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
Composition classes
• Composition involves constructing classes that contain
instances of other classes, promoting code reuse through
"has-a" relationships.
• Key Concepts:
-When you need to use functionalities of other classes without
inheriting from them..
-More flexible and modular, easy to change parts of the system.
-Useful when you want to build complex behavior by combining
simple components.
-Loosely coupled (components can be replaced easily).
class Engine:
def start(self):
print("Engine starting...")
def stop(self):
print("Engine stopping...")
class Car:
def __init__(self, model):
self.model = model
self.engine = Engine() # Car "has an" Engine
def start(self):
self.engine.start()
print(f"{self.model} is ready to go!")
def stop(self):
self.engine.stop()
print(f"{self.model} has stopped.")
car = Car("Toyota")
car.start()
Output:
Engine starting...
Toyota is ready to go!
car.stop()
Output:
Engine stopping...
Toyota has stopped.
Method Overriding
• defining a method in a subclass with the same
name as the one in its superclass.
• The subclass method then overrides the
superclass method.
class Animal:
def speak(self):
print("Animal Speaking!")
class Dog(Animal):
def speak(self):
print("Dog barking!")
obj = Dog()
Obj.speak()
0/p:Dog barking!
Data Abstrction
• Data abstraction in Python is a fundamental concept in object-
oriented programming (OOP) that allows you to hide the
internal details of how a class works and expose only what is
necessary to the user
• It helps in reducing complexity and increasing efficiency by
exposing only relevant details while hiding the
implementation specifics.
• data abstraction is achieved using abstract classes and
abstract methods
• abc (Abstract Base Classes) module is used for abstraction
• Abstract Class:
Abstract class is a class in which one or more abstract methods
are defined. When a method is declared inside the class without
its implementation is known as abstract method.
Abstract class cannot be instantiated.
• Abstract Method:
A method declared in an abstract class that has no
implementation and must be overridden by subclasses.
1.Using ABC Module:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
def stop(self):
print("Car stopped")
class Bike(Vehicle):
def start(self):
print("Bike started")
def stop(self):
print("Bike stopped")
# Usage
car = Car()
car.start() # Output: Car started
car.stop() # Output: Car stopped
bike = Bike()
bike.start() # Output: Bike started
bike.stop() # Output: Bike stopped