1 year ago
#381430
rkachach
How python handles decorators during class construction
I'm doing some tests with decorators on class methods. Following is a code sample:
def my_decorator(prefix):
def my_command(prefix):
print(f'my_command is called with {prefix}')
return lambda func: print(prefix)
return my_command
class MyClass():
def __init__(self):
print('MyClass ctr')
@my_decorator('cmd 1')
def _method_1():
pass
@my_decorator('cmd 2')
def _method_2():
pass
print("=================")
m = MyClass()
When I execute the code I got the following output:
my_command is called with <function MyClass._method_1 at 0x7f99a1f1f040>
my_command is called with <function MyClass._method_2 at 0x7f99a1f1f160>
=================
MyClass ctr
It seems that the decorators of all the methods are called before calling the class ctr (__init__
method).
Is this the default behavior? Why are decorators being called during the class creation process?
python
python-decorators
0 Answers
Your Answer