1#To create a static method, just add "@staticmethod" before defining it.
2
3>>>class Calculator:
4 # create static method
5 @staticmethod
6 def multiplyNums(x, y):
7 return x * y
8
9>>>print('Product:', Calculator.multiplyNums(15, 110))
10Product:1650
1class Calculator:
2
3 # create addNumbers static method
4 @staticmethod
5 def addNumbers(x, y):
6 return x + y
7
8print('Product:', Calculator.addNumbers(15, 110))
9
1import random
2
3class Example:
4 # A static method doesn't take the self argument and
5 # cannot access class members.
6 @staticmethod
7 def choose(l: list) -> int:
8 return random.choice(l)
9
10 def __init__(self, l: list):
11 self.number = self.choose(l)
1# python static method in simple explanation
2class cls:
3 @staticmethod
4 def func():
5 pass
6
7instance1 = cls()
8instance2 = cls()
9instance3 = cls()
10
11print(id(cls.func), cls.func)
12print(id(instance1.func), instance1.func)
13print(id(instance2.func), instance2.func)
14print(id(instance3.func), instance3.func)
15# they are same thing
1class Calculator:
2
3 def addNumbers(x, y):
4 return x + y
5
6# create addNumbers static method
7Calculator.addNumbers = staticmethod(Calculator.addNumbers)
8
9print('Product:', Calculator.addNumbers(15, 110))
10