There are different types of methods that are used while defining a class. They are
Instance method
Class method
Static method
Instance Method
Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute, let us see an example
class Student:
def __init__(self,name):
self.name = name
def printinfo(self):
self.city = 'Delhi'
print('my name is {} and from {}'.format(self.name,self.city))
def printcity(self):
print('my city is ', self.city)stud1 = Student('tom')
output
my name is tom and from Delhi
class method
It is one of the rarely used methods, where we use cls instead of self and we use class variables @ classmethod →constructor which we use as a decorator let us see an example
class Student:
Studentcount = 10
@classmethod
def printcount(cls):
print('class is having {} number of students'.format(cls.Studentcount))
class is having 10 number of students
output
class is having 10 number of students
static method
In this method, we can pass generic variables in the place of self where we can use it like defining functions normally, as you have to pass the arguments while calling it.
class Student:
@staticmethod
def printname(x):
print(‘student's name is {}{}’.format(x))Student.printname('Gokul')
Output
student's name is Mr.Gokul
Congrats🎉, On Learning the Types of methods in python classes with example programs.
Happy Learning :)