Python Chap 5
Python Chap 5
python
Chapter 5
Object oriented Programming
• Overview of OOP (Object Oriented Programming):
• 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):
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.
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()
# increment
geeks.counter += 1
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.
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)
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")
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
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