Skip to content

Commit 8a9ef25

Browse files
authored
Add example of class method self-decoration
1 parent e8818f0 commit 8a9ef25

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

docs/cheatsheet/decorators.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,39 @@ def foo(bar):
102102

103103
## Class based decorators
104104

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+
class DecorateMyMethod:
109+
110+
def decorator_for_class_method(method):
111+
def wrapper_for_class_method(self, *args, **kwargs)
112+
try:
113+
return method(self, *args, **kwargs)
114+
except Exception as 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+
def class_action(self):
124+
if self.succeed:
125+
print("You succeeded by choice.")
126+
else:
127+
raise Exception("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+
105138
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:
106139

107140
```python

0 commit comments

Comments
 (0)