Static Methods python code example

Example 1: static class python

#To create a static method, just add "@staticmethod" before defining it.

>>>class Calculator:
    # create static method
    @staticmethod
    def multiplyNums(x, y):
        return x * y

>>>print('Product:', Calculator.multiplyNums(15, 110))
Product:1650

Example 2: static methods in python

class Calculator:

    # create addNumbers static method
    @staticmethod
    def addNumbers(x, y):
        return x + y

print('Product:', Calculator.addNumbers(15, 110))

Example 3: staticmethod python

import random

class Example:
  	# A static method doesn't take the self argument and
    # cannot access class members.
	@staticmethod
    def choose(l: list) -> int:
    	return random.choice(l)
    
    def __init__(self, l: list):
      self.number = self.choose(l)

Example 4: instance method in python

# Instance Method Example in Python 
class Student:
    
    def __init__(self, a, b):
        self.a = a
        self.b = b 
    
    def avg(self):
        return (self.a + self.b) / 2

s1 = Student(10, 20)
print( s1.avg() )

Example 5: static methods in python

class Calculator:

    def addNumbers(x, y):
        return x + y

# create addNumbers static method
Calculator.addNumbers = staticmethod(Calculator.addNumbers)

print('Product:', Calculator.addNumbers(15, 110))