Python Method Types

The purpose of a python method is to process the variables provided in the class or in the method. We already know that the variables declared in the class are called class variables (or static variables) and the variables declared in the constructor are called instance variables.

We can classify the python methods in the following 3 types:

  1. Instance Methods
  2. Class Methods
  3. Static Methods

Instance Methods

Instance methods are the methods which act upon the instance variables of the class. Instance methods are bound to instances (or objects) and hence called as:

instancename.method()

Since instance variables are available in the instance, instance methods need to know the memory address of the instance. This is provided through 'self' variable by default as first parameter for the instance method. While calling the instance methods, we need not pass any value to the 'self' variable.

Instance Method example:

A Python program using a student class with instance methods to process the data of several students.

CopiedCopy Code
class Student: 
   def __init__(self, n = ' ', m=0): 
      self.name = n 
      self.marks = m 
   def display(self): 
      print('Hi', self.name) 
      print('Your marks', self.marks) 
   def calculate(self): 
      if(self.marks>=600): print('You got first grade')
      elif(self.marks>=500): print('You got second grade')     
      elif(self.marks>=350): print('You got third grade') 
      else: print('You are failed') 
n = int(input('How many students? ')) 
i=0 
while(i < n): 
	name=input('Enter name: ') 
	marks=int(input('Enter	marks: ')) 
	s=Student(name, marks) 
	s.display() 
	s.calculate()	
	i+=1 
	print('---------------------')

Python Instance methods are of two types:

  1. Accessor methods.
  2. mutator methods.

Accessor methods simply access or�read data�of the variables. They do not modify the data in the variables. Accessor methods are generally written in the form of getXXX() and hence they are also called getter methods. For example,

def getName(self): 
    return self.name 

Here, getName() is an accessor method since it is reading and returning the value of 'name' instance variable. It is not modifying the value of the name variable.

On the other hand, mutator methods are the methods which not only read the data but also modify them. They are written in the form of setXXX() and hence they are also called setter methods. For example,

def setName(self, name): 
   self.name = name 

Here, setName() is a mutator method since it is modifying the value of 'name' variable by storing new name. In the method body, 'self.name' represents the instance variable 'name' and the right-hand side 'name' indicates the parameter that receives the new value from outside.

CopiedCopy Code
class Student: 
	def setName(self, name): 
	    self.name = name 
	def getName(self): 
	    return self.name 
	def setMarks(self, marks): 
	    self.marks = marks 
	def getMarks(self): 
	    return self.marks 
n = int(input('How many students?')) 
i=0 
while(i< n): 
	s=Student() 
	name=input( 'Enter name: ') 
	s.setName(name)
	marks=int(input( 'Enter marks: ')) s.setMarks(marks)
	print('Hi', s.getName()) print('Your marks', s.getMarks()) i+=1
	print('-------------------')

Since mutator methods define the instance variables and store data, we need not write the constructor in the class to initialize the instance variables. This is the reason we did not use constructor in Student class

Class Methods

These methods act on class level. Class methods are the methods which act on the class variables or static variables.

These methods are written using @classmethod decorator above them. By default, the first parameter for class methods is 'cls' which refers to the class itself. For example, 'cls.var' is the format to refer to the class variable. These methods are generally called using the�classname.method()�.

Example:

A Python program to use class method to handle the common feature of all the instances of Bird class.

class Bird:

wings = 2

@classmethod

def fly(cls, name):

print('{} flies with {} wings'.format(name, cls.wings))

Bird.fly('Sparrow')

Bird.fly('Pigeon')

Static Methods

We need static methods when the processing is at the class level but we need not involve the class or instances. Static methods are used when some processing is related to the class but does not need the class or its instances to perform any work.

Setting environmental variables, counting the number of instances of the class or changing an attribute in another class, etc. are the tasks related to a class. Such tasks are handled by static methods. Also, static methods can be used to accept some values, process them and return the result. In this case the involvement of neither the class nor the objects is needed.

Static methods are written with a decorator @staticmethod above them. Static methods are called in the form of classname.method().

Examples:

A Python program to create a static method that counts the number of instances created for a class.

CopiedCopy Code
 class Myclass: 
   n=0 
   def __init__(self): 
      Myclass.n = Myclass.n+1 
   @staticmethod 
   def noObjects(): 
      print('No. of instances created: ', Myclass.n) 
obj1 = Myclass() 
obj2 = Myclass() 
obj3 = Myclass() 
Myclass.noObjects()

A Python program to create a static method that calculates the square root value of a given number.

CopiedCopy Code
#a static method to find square root value 
import math 
class Sample: 
   @staticmethod 
   def calculate(x):
      result = math.sqrt(x) 
      return result 
num = float(input('Enter a number:')) 
res = Sample.calculate(num) 
print('The square root of {} is {:.2f}'.format(num, res))