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)
1class Float:
2 def __init__(self, amount):
3 self.amount = amount
4
5 def __repr__(self):
6 return f'<Float {self.amount:.3f}>'
7
8 @classmethod
9 def from_sum(cls, value_1, value_2):
10 return cls(value_1 + value_2)
11
12
13class Dollar(Float):
14 def __init__(self, amount):
15 super().__init__(amount)
16 self.symbol = '€'
17
18 def __repr__(self):
19 return f'<Euro {self.symbol}{self.amount:.2f}>'
20
21
22print(Dollar.from_sum(1.34653, 2.49573))
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
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