Decorators in Python
Decorator in Python or Aspects in other programming languages like Java. But still I think Decorator in Python is more like Decorator than in Java. In Java, I see people believe a Deorator pattern to be applicable to objects only. And I believe & say, that you do 'Decorator' when either you add/modify the behavior of an object at runtime or you override methods of parent class using inheritance. And when you do at object level or class level, you still use inheritance & can do decoration of that hierarchy only, while in Aspect oriented programming, we say that we will do this for every kind of object.
Similarly in Python, Decorator does.
A simple example is given below -
def counters(n):
def counters(n):
def inner(func):
def wrapper(*args, **kwargs):
print('Interaction starts')
for _ in range(n):
res = func(*args, **kwargs)
if str(func).__contains__('greet'):
print('How are you?')
print('Decorator interaction ends....')
return res
return wrapper
return inner
@counters(3)
def greet(name):
print(f'Hello {name}')
@counters(2)
def bbye(name, what):
print(f'BBye {name}, {what} your day')
if __name__ == '__main__':
greet('<Name>')
bbye('<Name>', 'Enjoy')
In such decorators, one can have some generic behavior like time taken to execute a method or to log some information around method execution.
Similarly in Python, Decorator does.
A simple example is given below -
def counters(n):
def counters(n):
def inner(func):
def wrapper(*args, **kwargs):
print('Interaction starts')
for _ in range(n):
res = func(*args, **kwargs)
if str(func).__contains__('greet'):
print('How are you?')
print('Decorator interaction ends....')
return res
return wrapper
return inner
@counters(3)
def greet(name):
print(f'Hello {name}')
@counters(2)
def bbye(name, what):
print(f'BBye {name}, {what} your day')
if __name__ == '__main__':
greet('<Name>')
bbye('<Name>', 'Enjoy')
In such decorators, one can have some generic behavior like time taken to execute a method or to log some information around method execution.