Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8a9ef25

Browse files
authored
Add example of class method self-decoration
1 parente8818f0 commit8a9ef25

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+
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+
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)

[8]ページ先頭

©2009-2025 Movatter.jp