OBJECT ORIENTED
PROGRAMMING CONCEPTS IN PYTHON
• Python is a multi-paradigm programming language. Meaning, it supports
different programming approach.
• One of the popular approach is Object-Oriented Programming (OOP).
• Class Definition: A class specifies the set of instance variables and methods
that are “bundled together” for defining a type of object.
• Python class is a blueprint of an object.
• Class is a keyword
Class
Syntax for creating a Class:
class <Classname>:
data1 = value1
...
dataM = valueM
def <function1>(self,arg1,...,argK):
<block>
...
def <functionN>(self,arg1,...,argK):
<block>
Example:
class Maths:
a=10
b=20
def subtract(self,i,j):
return i-j
def add(self,x,y): # Argument (self) refers to the object itself
return x+y
Example:
class Maths:
pass # Empty class
Object : An object is simply a collection of data (variables) and methods
(functions) that act on those data.
• An object is also called an instance of a class
• Syntax:
Objectname=classname()
Example:
obj=Math()
Call the variable and function in a class using the following
Syntax:
Objectname.variablename
Objectname.functionname()
Example:
obj.a
obj.substract(1,2)
obj.add(1,2)
Example 1:
class Print:
def p1(self):
print("Hello World")
ob=Print()
ob.p1() Output: Hello World
Example 2:
class Maths:
def subtract(self,i,j):
return i-j
ob=Math()
ob.subtract(8,4) O/p: 4
class Maths:
def subtract(self,i,j):
return i-j
def testsub(self):
print self.subtract(8,4)
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
# Creating an object of the Dog class
dog1 = Dog("Buddy", 3)
print(dog1.name)
print(dog1.species)