python decorator class method code example
Example 1: python decorator
def logging(f):
def decorator_function(*args, **kwargs):
print('executing '+f.__name__)
return f(*args, **kwargs)
return decorator_function
@logging
def hello_world():
print('Hello World')
Example 2: python decorator in class with self
class Dog:
def __init__(self, name):
self.name = name
def say_name(func):
def decorator(*args, **kwargs):
self = args[0]
print(self.name)
return func(*args, **kwargs)
return decorator
@say_name
def bark(self):
print('woof!')
Example 3: python decorator
import functools
def repeat(num_times):
def decorator_repeat(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(num_times):
result= func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
@repeat(num_times= 3)
def greet(name):
print(f"Hello {name}")
greet("thomas")