
Instance Method
They are most widely used methods. Instance method receives the instance of the class as the first argument, which by convention is called self.
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')
stud1.printinfo()
Output:
my name is tom and from delhi
class method
Class methods don't need self as an argument, but they do need a parameter called cls.
This stands for class, and like self, gets automatically passed in by Python.
Class methods are created using the @classmethod decorator.
class Student:
Studentcount = 10
@classmethod
def printcount(cls):
print('class is having {} number of students'.format(cls.Studentcount))
Student.printcount()
Output:class is having 10 number of students
class Student:
Studentcount = 0
def __init__(self):
Student.Studentcount += 1
@classmethod
def printcount(cls):
print('class is having {} number of students'.format(cls.Studentcount))
stud1 = Student()
stud2 = Student()
Student.printcount()
class is having 2 number of students
Stud1.printcount() #using instance and calling class method
class is having 2 number of students
static method
This type of method takes neither a self
nor a cls
parameter (but of course it’s free to accept an arbitrary number of other parameters).
Therefore a static method can neither modify object state nor class state. Static methods are restricted in what data they can access
class Student:
@staticmethod
def printname(x):
print('student name is {}{}'.format(x))
@staticmethod
def printage(x):
print('student age is {}{}'.format(x))
Student.printname('sam')
student name is Mr.sam
Comments
Post a Comment