Class and object in python

Dineshbaburam
2 min readMar 16, 2022

Class

A class is a blueprint from which specific objects are created. Classes allow us to logically group our data and function to reuse and way to build upon if we need to be.

Object

Objects are instances of the class.

The class allows grouping the data (Name, age, and salary). The object is created for each instance of the class.

What is an instance?
Class act as a template, when you fill in details it becomes an instance.

The syntax for class:

class class_name:
stmt 1
stmt 2

Example 1:

class Student:
pass

stud = Student()
stud1 = Student()

stud.first = "Ram"
stud.last = "kumar"
stud1.first = "Gandhi"
stud1.last = "Mahan"

print(stud.first)
print(stud1.last)

In the above example, Student is the class variable. stud and stud1 are the objects for each class. stud.first, stud.last, stud1.first and stud1.last are the instance variable.
The output

Ram
Mahan

Example 2:

class Student:
def __init__(self, first, last):
self.first = first
self.last = last

stud = Student("ram", "kumar")
stud1 = Student("Gandhi", "mahan")

print(stud.first)
print(stud1.last)

__init()__ is an initialized method or constructor to the class which will invoke automatically when an object is created.

The output:

ram
mahan

Example 3:

class Student:
mark = 30;
def __init__(self, first, last):
self.first = first
self.last = last

def full_name(self):
return self.first + " " +self.last

stud = Student("Ram", "kumar")
stud1 = Student("Gandhi", "mahan")

print(stud.full_name())
print(stud1.full_name())
print(stud.__dict__)
print(Student.__dict__)

In the above example, “mark” is the class variable that can be used in all functions of the class. full_name() is the method that can be created inside the class. self. first and self. last are the instance variable of the class object.

Ram kumar
Gandhi mahan
{'first': 'Ram', 'last': 'kumar'}
{'__module__': '__main__', 'mark': 30, '__init__': <function Student.__init__ at 0x10a9e4378>, 'full_name': <function Student.full_name at 0x10a9e42f0>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}

--

--