-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator_class.py
67 lines (52 loc) · 1.71 KB
/
decorator_class.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class PlayerCharacter:
membership = True # class object attribute
# constructor
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age # instance attribute
def run(self):
print(f'run started by {self.name}')
return 'done'
# the way we can define common methods for all the objects
# of this class is that we use decorators like @classmethod
# or something like @staticmethod and then define the
# the method with the specified description of the
# decorator. For example:
@classmethod
def new_object(cls, num1, num2):
'''
1st param of a classmethod is always by convention
known as cls, which is used to create an instance
variable (object) of this class, which we will see
below.
'''
return cls('Teddy', num1 + num2) # instantiated an object of type PlayerCharacter
'''
We also have @staticmethod which cannot create a new
instance of the class and therefore doesn't take in cls
by default and so, it can do normal stuff as shown below
'''
@staticmethod
def adding_things(num1, num2):
return num1 + num2
# usage of classmethod
print(PlayerCharacter.new_object(20, 30)) # memloc of object
p1 = PlayerCharacter('Ram', 25)
p2 = PlayerCharacter.new_object(2, 3)
print(p1.new_object(20, 5).name) # Teddy
print(p2.age) # 5
'''
We can see that the classmethod can be used by both the
instance and the class itself and can be called to do what it's
defined to do.
'''
# usage of staticmethod
print(PlayerCharacter.adding_things(7, 3)) # 10
'''
Output:
------
<__main__.PlayerCharacter object at 0x008BA130>
Teddy
5
10
'''