Concept of OOPS in python
Objects and Classes in python
Python is an object oriented programming language, almost everything in python is object , with properties and methods. Class is like a template or blueprint to create objects
class MyClass:
x = 5obj1 = MyClass()
print(obj1.x)
o/p: 5
Introduction to OOPS
Approach to solving problems using objects is called OOPs. Object has two parts : Attributes and Behavior. Main concept is Re usability of code
Ex: Car object : Attributes- color,model, size, plate_number etc. Behavior — drive(),stop() etc
Basic principles of OOPs
- Class
- object
- Inheritance
- Encapsulation
- Polymorphism
Real Life Example:
Every Human Being can be classified as Male or Female
Each have common body features such as Heart, eyes , legs etc And Same Functions such as talk,hear , walk , see etc
In this case Human being is a Class and common body features and functions are class attributes.
Both Male and Female are inherited from parent class Human Being. when we actualize a Male it has physical existence called object. Ex- Name : xyz age :24 is a object and Male is class a logical definition
We don't know the details of how to walk, listen , see etc its hidden . this concept is called encapsulation, Used for security reason and to avoid overwhelming end users
Consider Female class object, it can behave in many ways such as a woman , wife, mother, engineer etc at the same time ,This is called polymorphism.
Concept of Classes and Objects in python
- objects is the basic unit of OOP, object represents a particular instance of a class.
- There can be more than one instance of an object.
- Each instance of an object can hold its own relevant data.
- Objects with similar properties and methods are grouped together to form a class.
Syntax:
class ClassName:
…
obj1 = className()
#defining a class
class classname:
var = "This is a class variable"
def func(self):
print("I am inside the class")#creating a Object
obj1 =classname();
obj1.var
o/p: 'This is a class variable'obj2 =classname();
#Accessing class members
obj2.var = "updated variable"
print(obj1.var)
print(obj2.var)
o/p: This is a class variable
updated variable##Example 2 - Constructor/Init method - invoked at the time of #object creation , generally used to initialize values
class Student:
def __init__(self,name,branch,year):
self.n=name
self.b=branch
self.y=year
def print_func(self):
print("Name : ",self.n)
print("Branch :",self.b)
print("Year :", self.y)obj1 = Student("Paul","CSE","2019")
obj1.print_func()
o/p:
Name : Paul
Branch : CSE
Year : 2019##Example3
class Vehicle:
name =""
Kind ="car"
value =100
def description(self):
desc_str ="%s is a %s worth of %d" %(self.name,self.Kind,self.value)
return desc_str
def setValues(self,n,k,v):
self.name=n
self.Kind=k
self.value=vv =Vehicle()
v.setValues("a","car",222222)
print(v.description())
o/p: a is a car worth of 222222
Inheritance-
One class inheriting the properties of another class.
Single Inheritance — single class inherits from single parent
class fruit:
def __init__(self):
print("I am the parent class")
class citrus(fruit):
def __init__(self):
super().__init__()
print("I am citrus and belong to fruit class")
obj =citrus()
o/p: I am the parent class
I am citrus and belong to fruit class
Multiple Inheritance — class inherits from multiple Parent classes
class A:
pass
class B:
pass
class C(A,B):
pass
issubclass(C,A) and issubclass(C,B)
o/p: True
Multilevel — one class inherits from another which in turn inherits from another
class A:
x=1
class B(A):
pass
class C(B):
pass
obj1 = C()
obj1.xo/p: 1
Hierarchical — more than one class inherits from a class
class A:
x=1
class B(A):
pass
class C(A):
pass
obj1 = C()
print(obj1.x)
issubclass(B,A) and issubclass(C,A)
o/p: 1
True
Hybrid — Combination of any two types of Inheritance
class A:
x=1
class B(A):
pass
class C(A):
pass
class D(A):
pass
# b, c ,d are having hierarchial inheritance
class E(B,D):
pass
# e is having multiple inheritance
objE= E()
objE.x
o/p: 1
Inheritance Super Function — Used to call method/variable from a parent class
class Vehicle:
wheel =2
def start(self):
print("starting engine")
def stop(self):
print("stopping engine")
class bike(Vehicle):
def say(self):
super().start()
print("I have wheels %s"%(super().wheel))
super().stop()
h= bike()
h.say()
o/p: starting engine
I have wheels 2
stopping engine
Overloading : Same function with different parameters
#Unlike Java this way of overriding doesnt work
def add(a,b):
return a+b
def add(a,b,c): #updated the memory
return a+b+cadd(2,3)o/p:
TypeError: add() missing 1 required positional argument: 'c'#Overloading to resolve the above issue
def add(instanceOf, *args):
if instanceOf == 'int':
result =0
if instanceOf == 'str':
result =''
if instanceOf == 'float':
result =0.0
for i in args:
result+=i
return resultadd('str','1','2','1','2')
add('int',1,2,1,2)
o/p: 1212
6
Overriding- Subclass can change the method of the parent class
class A:
def checkit(self):
print("I am inside A")
class B:
def checkit(self,b):
print("I am inside B")
a=A();
b=B();
b.checkit(2)
a.checkit()o/p:I am inside B
I am inside A
Encapsulation —
Abstraction + Data Hiding. Abstraction is the process of showing essential features to the user and hiding non essential features from the user. Ex: use of API , BE logic is not shown to end user.
Wrapping up of data ,methods in a single unit is called Encapsulation. Ex: Car wraps many components such as wheels, engine,chasis etc
Private variables are prefixed with underscore
class Encap:
def __init__(self):
self.a=123
self._b=123
self.__c=123
obj1 =Encap()
print(obj1.a,obj1._b)
print(obj1._Encap__c)
print(obj1.c,obj1.__c)
o/p:
123 123
123
...
AttributeError: 'Encap' object has no attribute 'c'
Accessing private method and variables
class Car:
__maxspeed=0
__name = ''
def __init__(self):
self.__maxspeed =200
self.__name ="Supercar"
def drive(self):
print("maxspeed of car is",self.__maxspeed)
def setMaxSpeed(self,speed):
self.__maxspeed =speed
def __privateKey(self):
print("private key is XXXX")obj1 = Car()
obj1.drive()
o/p: maxspeed of car is 200obj1.__maxspeed =300
print(obj1._Car__maxspeed)
o/p: 200obj1.setMaxSpeed(300)
obj1.drive()
o/p: maxspeed of car is 300obj1._Car__privateKey()
o/p: private key is XXXX
Polymorphism
Functions with same name but functioning in different ways
class Shark(fishes):
def swim(self):
print("Shark can swim")
def bones(self):
print("Shark has soft cartillages")
class clownfish(fishes):
def swim(self):
print("Clownfishes can swim")
def bones(self):
print("clownfish has bones")def intheocean(fish):
fish.swim()s1 =Shark()
c1=clownfish()
intheocean(s1)
intheocean(c1)
o/p:
Shark can swim
Clownfishes can swim
Note: some Inner working of operators
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __sub__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
p1 = Point(3, 4)
p2 = Point(1, 2)
result = p1-p2
print(result.x, result.y)o/p:
4 6
def outerFxn():
global a
a = 20
def innerFxn():
global a
a = 30print('a =', a)
a = 10
innerFxn()
print('a =', a)o/p:
20
30