Class, Objects, and Methods in Python
A class is a template for creating objects or a collection of objects.
Objects have member variables and methods associated with them. In python, a class is created by using keyword class. An object is created using the constructor of the class. This object will then be called the instance of the class.
# using OOP – Class example in Python
class Emp:
def __init__(self, name, age):
self.name = name
self.age = age
# object is being created here as e1.
e1 = Emp(“Ram”, 31)
# printing all class members
print(e1.name)
print(e1.age)
OUTPUT:
Ram
31
# Python class with Method body
class TestClass:
def func1(self):
print(‘Inside the function 1, part of TestClass ‘)
print(‘Function 1 over!!!!’)
def func2(self):
print(‘Inside the function 2, part of TestClass ‘)
print(‘Function 2 over!!!!’)
# create a new TestClass object
ob = TestClass()
# Calling functions through class instance
ob.func1()
ob.func2()
OUTPUT:
Inside the function 1, part of TestClass
Function 1 over!!!!
Inside the function 2, part of TestClass
Function 2 over!!!!
# class with method
class Emp:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print(“Hello my name is ” , self.name,”and I am”,self.age,”year old” )
e1 = Emp(“Ram”, 32)
e1.myfunc()
OUTPUT:
Hello my name is Ram and I am 32 year old
# class with methods to raise salary by 5%
class employee:
def __init__(self, first, last, sal):
self.fname=first
self.lname=last
self.sal=sal
self.email=first + ‘.’ + last + ‘@mitindia.in’
def detail(self):
return ‘{}’.format(self.email)
def apply_hike(self):
self.sal=int(self.sal*(5/100)+self.sal)
emp1=employee(‘Venkat’,’joshi’,35000)
emp2=employee(‘Sham’,’KK’,15000)
print(emp1.detail())
print(‘Before Hike:’,emp1.sal)
emp1.apply_hike()
print(‘After Hike:’,emp1.sal)
print(emp2.detail())
print(‘Before Hike:’,emp2.sal)
emp2.apply_hike()
print(‘After Hike:’,emp2.sal)
OUTPUT:
Venkat.joshi@mitindia.in
Before Hike: 35000
After Hike: 36750
Sham.KK@mitindia.in
Before Hike: 15000
After Hike: 15750
# Class student example
class Student:
def __init__(std, roll, sname, course):
std.roll=roll
std.sname=sname
std.course=course
s1=Student(1002, ‘Aditya’, ‘PGP-Business Analytics’)
print(‘Roll Number:’, s1.roll)
print(‘Name:’,s1.sname)
print(‘Course:’, s1.course)
OUTPUT:
Roll Number: 1002
Name: Aditya
Course: PGP-Business Analytics
# class without init method and use of pass keyword for not declaring method in class
class Student:
pass
# Creating objects s1 and s2 here on class Student
s1=Student()
s2=Student()
s1.fname=’Vasudeva’
s1.course=’Business Intelligence’
s2.fname=’John’
s2.course=’Artificial Intelligence’
print(‘Student 1 Details’)
print(s1.fname)
print(s1.course)
print(‘Student 2 Details’)
print(s2.fname)
print(s2.course)
OUTPUT:
Student 1 Details
Vasudeva
Business Intelligence
Student 2 Details
John
Artificial Intelligence