-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecoratorClass.py
executable file
·71 lines (51 loc) · 1.32 KB
/
DecoratorClass.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
68
69
70
71
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 19:14:04 2021
@author: maherme
"""
#%%
def my_dec(a, b):
def dec(fn):
def inner(*args, **kwargs):
print("decorated function called a={0}, b={1}".format(a, b))
return fn(*args, **kwargs)
return inner
return dec
@my_dec(10, 20)
def my_func(s):
print("Hello {0}".format(s))
my_func('World')
#%%
# We can use a class callable using the __call__ method:
class MyClass:
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, c):
print("called a={0}, b={1}, c={2}".format(self.a, self.b, c))
obj = MyClass(10, 20)
obj.__call__(100)
obj(100) # We can do this because we are using __call__, so MyClass is callable.
#%%
# So we can use a class as a decorator in the following way:
class MyClass:
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, fn):
def inner(*args, **kwargs):
print("decorated function called a={0}, b={1}".format(self.a, self.b))
return fn(*args, **kwargs)
return inner
@MyClass(10, 20)
def my_func(s):
print("Hello {0}".format(s))
my_func('World')
#%%
obj = MyClass(10, 20)
def my_func(s):
print("Hello {0}".format(s))
my_func = obj(my_func)
my_func('World')
#%%