- @
def decorator(func):
return func
@decorator
def some_func():
pass
Is equivalent to this code :
def decorator(func):
return func
def some_func():
return pass
some_func=decorator(some_func)
Example :
class Pizza(object):
def __init__(self):
self.toppings=[]
def __call__(self, topping):
self.toppings.append(topping())
def __repr__(self):
return str(self.toppings)
pizza=Pizza()
@pizza
def cheese():
return 'cheese'
@pizza
def sauce():
return 'sauce'
print(pizza)
>>>
['cheese', 'sauce']
class DatetimeDecorator:
def __init__(self, f):
self.func=f
def __call__(self, *args, **kwargs):
print(datetime.datetime.now())
self.func(*args, **kwargs)
print(datetime.datetime.now())
class MainClass:
@DatetimeDecorator
def main_function_1():
print('main function 1 starts')
@DatetimeDecorator
def main_function_2():
print('main function 2 starts')
my=MainClass()
my.main_function_1()
my.main_function_2()
>>>
2021-12-21 06:17:35.554216
main function 1 starts
2021-12-21 06:17:35.555863
2021-12-21 06:17:35.556337
main function 2 starts
2021-12-21 06:17:35.556954
'Basic Python' 카테고리의 다른 글
union, intersection (0) | 2022.03.10 |
---|---|
swapcase (0) | 2021.12.22 |
itertools.islice, chain, isinstance (0) | 2021.05.25 |
pip, pip search, pip list, pip freeze, pip install, pip show (0) | 2021.05.25 |
super, classmethod, abstractmethod, entity (0) | 2021.05.24 |