Python static Method

We need python 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() .

Simple Static Method

Python simple static method example:

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

Static Method

Python static method example:

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))
Instance method example
CopiedCopy Code

import sys 
class Bank(object): 
   #to initialize name and balance instance vars 
   def __init__(self, name, balance=0.0): 
      self.name = name 
      self.balance = balance 
   #to add deposit amount to balance 
   def deposit(self, amount): 
      self.balance += amount 
      return self.balance 
   #to deduct withdrawal amount from balance 
   def withdraw(self, amount): 
      if amount >self.balance: 
         print('Balance amount is less, so no withdrawal.') 
      else:
        self.balance -= amount 
      return self.balance 
#using the Bank class
 #create an account with the given name and balance 0.00 
name = input('Enter name:') 
b = Bank(name) 
#this is instance of Bank class 
#repeat continuously till choice is 'e' or 'E'. 
while(True): 
   print('d -Deposit, w -Withdraw, e -Exit') 
   choice = input('Your choice:') 
   if choice == 'e' or choice == 'E': 
      sys.exit() 
#amount for deposit or withdraw 
   amt = float(input('Enter amount:')) 
#do the transaction 
   if choice == 'd' or choice == 'D': 
      print('Balance after deposit:', b.deposit(amt)) 
   elif choice == 'w' or choice == 'W': 
      print('Balance after withdrawal:', b.withdraw(amt))