Types of methods
In python different types of methods are available.
Instance method:
The method which work upon instance variable is called instance method. The instance method is invoked with use of instance variable and dot operator.
In instance method the first argument is self, that refers to the current instance.
There are two types of instance methods:
Access or method / getter method:
Accessor method simply read the data or access the data. These method do not update or modify the data. These methods are written in the form of get… so it is also called getter method.s
Mutator method/ setter method:
These method do not only read data but also update or modify the data. These methods can set the data so these are called setter method also.
Example:
class book:
def setid(self,id):
self.id=id
def setname(self,name):
self.name=name
def getid(self):
return self.id
def getname(self):
return self.name
b1=book()
x=int(input("Enter id"))
y=input("Enter name")
b1.setid(x)
b1.setname(y)
print("The book id is ",b1.getid(),"and book name is ", b1.getname())
Output:
Enter id 1
Enter name abc
The book id is 1 and book name is abc
2. Class method
These method work on class level. This method work on class variable or static variable. This method written using @classmethod decorator.
The first variable is cls by default.
The class method is called using class name.
Class method is used to handle the processes that are required by all the instances. The common task for all the instances is handle by the class method.
class emp:
salary=10000
@classmethod
def setsalary(cls,sal):
print("your salary is ",sal,"Min salary is ",cls.salary)
e1=emp()
x=int(input("Enter salary"))
emp.setsalary(x)
Static method
Static method is used to process class level. It is same as class method but this method not involve class or instances. Here cls is not used.
Static method written with decorator
@staticmethod
To call static method
Classname.methodname()
Example:
class countobj:
stvar=0
def __init__(self):
countobj.stvar=countobj.stvar+1
@staticmethod
def findtotobj():
print("The total number of objects are: ", countobj.stvar)
obj1=countobj()
obj2=countobj()
obj3=countobj()
countobj.findtotobj()
Passing members of one class to another
It is possible to pass one class instance variable of method to another class.
Example:
''' passing object of one class to another class with use of static method'''
class student:
def __init__(self):
self.id=1
self.name='abc'
def printdetails(self):
print("Id is",self.id,"Name is",self.name)
class student1:
@staticmethod
def printobj(s1):
s1.id=2
s1.name='def'
s1.printdetails()
s1=student()
s1.printdetails()
student1.printobj(s1)
s1.printdetails()
Output:
Id is 1 Name is abc
Id is 2 Name is def
Id is 2 Name is def