You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/cheatsheet/decorators.md
+33Lines changed: 33 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -102,6 +102,39 @@ def foo(bar):
102
102
103
103
##Class based decorators
104
104
105
+
To decorate a class methos, you must define the decorator within the class. When only the implicit argument`self` is passed to the method, without any other additional arguments, you must make a separate decorator for only those methods without any additional arguments. An example of this is when you want to catch and print exceptions in a certain way.
106
+
107
+
```python
108
+
classDecorateMyMethod:
109
+
110
+
defdecorator_for_class_method(method):
111
+
defwrapper_for_class_method(self,*args,**kwargs)
112
+
try:
113
+
return method(self,*args,**kwargs)
114
+
exceptExceptionas e:
115
+
print("\nWARNING: Please make note of the following:\n")
116
+
print(e)
117
+
return wrapper_for_class_method
118
+
119
+
def__init__(self,succeed:bool):
120
+
self.succeed= succeed
121
+
122
+
@wrapper_for_class_method
123
+
defclass_action(self):
124
+
ifself.succeed:
125
+
print("You succeeded by choice.")
126
+
else:
127
+
raiseException("Epic fail of your own creation.")
128
+
129
+
test_succeed= DecorateMyMethods(True)
130
+
test_succeed.class_action()
131
+
# You succeeded by choice.
132
+
133
+
test_fail= DecorateMyMethod(False)
134
+
test_fail.class_action()
135
+
# Exception: Epic fail of your own creation.
136
+
```
137
+
105
138
A decorator can also be defined as a class instead of a method. This is useful for maintaining and updating a state, such as in the following example, where we count the number of calls made to a method: