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# 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
1import numpy as np
2
3class Unknown:
4 def __init__(self, p1, p2, p3, p4):
5 self.p1 = p1
6 self.p2 = p2
7 self.p3 = p3
8 self.p4 = p4
9
10 def random_func(self, p5):
11 '''Function that return an array from a range,
12 with specified shape, and name'''
13 step1 = np.array(np.arange(self.p1)).reshape((self.p2,self.p3))
14 step2 = self.p4
15 print(step2)
16 print('Printing p5 =>', p5)
17 return step1
18
19 @classmethod
20 def a_class_method(self, p6):
21 print(f'This is a class method: {p6}')
22
23
24
25#PREPARE PARAMS
26# cust_arr = random_func(self.p1, self.p2, self.p3, self.p4)
27params = {'p1':12, 'p2':3, 'p3':4, 'p4':'Creating customized array with params'}
28
29#INSTANCIATE
30here = Unknown(**params)#16, 4, 4, 'This actually work too!')
31here.random_func('This is P5')
32Unknown.a_class_method('P6 value is now used !')