1class math:
2
3 @staticmethod
4 def add(x, y):
5 return x + y
6
7 @staticmethod
8 def add5(num):
9 return num + 5
10
11 @staticmethod
12 def add10(num):
13 return num + 10
14
15 @staticmethod
16 def pi():
17 return 3.14
18
19
20x = math.add(10, 20)
21y = math.add5(x)
22z = math.add10(y)
23print(x, y, z)
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)
1class point:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 @classmethod
7 def zero(cls):
8 return cls(0, 0)
9
10 def print(self):
11 print(f"x: {self.x}, y: {self.y}")
12
13p1 = point(1, 2)
14p2 = point().zero()
15print(p1.print())
16print(p2.print())
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
1# classmethod example
2In [20]: class MyClass:
3 ...: @classmethod
4 ...: def set_att(cls, value):
5 ...: cls.att = value
6 ...:
7
8In [21]: MyClass.set_att(1)
9
10In [22]: MyClass.att
11Out[22]: 1
12
13In [23]: obj = MyClass()
14
15In [24]: obj.att
16Out[24]: 1
17
18In [25]: obj.set_att(3)
19
20In [26]: obj.att
21Out[26]: 3
22
23In [27]: MyClass.att
24Out[27]: 3