Class and object in python


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.


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:

stud = Student()
stud1 = Student()

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


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


Example 2:

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

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


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

The output:


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")


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}



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store