2020-04-25_python-decorators-part-2.html
001|
002|
003|
004|
005| def MyDecorator (inner_function):
006| def wrapper (params):
007|
008| return inner_function(params)
009| return wrapper
010|
011| @MyDecorator
012| def some_function (params):
013|
014| return retval
015|
016|
017| def MyDecorator (inner_function):
018| def wrapper (params):
019|
020| retval = inner_function(params)
021|
022| return retval
023| return wrapper
024|
025|
026| @Encode(key1)
027| def function_1 (params):
028|
029| return retval
030|
031| @Encode(key2)
032| def function_2 (params):
033|
034| return retval
035|
036|
037| def Encode (encoding_key):
038| def decor (inner_function):
039| def wrapper (s):
040| s = encode_string(s, encoding_key)
041| return inner_function(s)
042| return wrapper
043| return decor
044|
045| @Encode(key1)
046| def function_1 (params):
047|
048| return retval
049|
050|
051| def MyDecorator (inner_function):
052| def wrapper (*args, **kwargs):
053|
054| return inner_function(*args, **kwargs)
055| return wrapper
056|
057|
058| @MyDecorator
059| def Alfa (a, b, c, **kwargs):
060|
061|
062| @MyDecorator
063| def Baker (x, y, **kwargs):
064|
065|
066| @MyDecorator
067| def Charlie (s, **kwargs):
068|
069|
070| Alfa(21, 42, -18)
071| Baker(y=+0.0013437, x=-0.75, debug=True)
072| Charlie(pre='foo', s='Hello, World!', post='bar')
073|
074|
075| def PrintArgs (inner_function):
076| def wrapper (*args):
077| name = inner_function.__qualname__
078| print('function: %s' % name)
079| for a in enumerate(args):
080| print('>>> [%d]: %s' % a)
081| return inner_function(*args)
082| return wrapper
083|
084| @PrintArgs
085| def Alfa (a, b, c):
086|
087|
088| @PrintArgs
089| def Baker (x, y):
090|
091|
092| @PrintArgs
093| def Charlie (s):
094|
095|
096| Alfa(21, 42, -18)
097| Baker(-0.75, +0.0013437)
098| Charlie('Hello, World!')
099|
100|
101| def PrintMethodArgs (method):
102| def wrapper (self, *args):
103| name = method.__qualname__
104| print('%s: %s' % (name, str(args)))
105| return method(self, *args)
106| return wrapper
107|
108| class Example (object):
109| @PrintMethodArgs
110| def method1 (self, a, b, c):
111|
112| @PrintMethodArgs
113| def method2 (self, x, y):
114|
115| @PrintMethodArgs
116| def method3 (self, s):
117|
118|
119|
120| def ClassDecorator (cls):
121| def wrapper (*args):
122| return cls(*args)
123| return wrapper
124|
125| @ClassDecorator
126| class Example (object):
127|
128|
129|
130|