There is a problem today , You want to put all the following functions in a class , All with trimmers . Because there are many functions in the class , Every function is @ It feels very troublesome . After searching , I really found an elegant way !
def decorator(func):
def __logdec(self, *args, **kwargs):
print('【Start--------%s】' % func.__name__)
print("\n")
func(self, *args, **kwargs)
print("\n")
print('【End--------%s】' % func.__name__)
print("\n")
print("\n")
return __logdec
class AlienClass(object):
@decorator
def print_info(self, info):
print("--------->{}".format(info))
@decorator
def print_name(self, name):
print("===============>>{}".format(name))
@decorator
def xxxxxxxx():
# Omit here N A function ............
pass
alien = AlienClass()
alien.print_info("hello world !")
alien.print_name("alien")
# The end result is as follows :
【Start--------print_info】
--------->hello world !
【End--------print_info】
【Start--------print_name】
===============>>alien
【End--------print_name】
import inspect, types
def decorator(func):
def __logdec(self, *args, **kwargs):
print('【Start--------%s】' % func.__name__)
print("\n")
func(self, *args, **kwargs)
print("\n")
print('【End--------%s】' % func.__name__)
print("\n")
print("\n")
return __logdec
class AlienClass(object):
def print_info(self, info):
print("--------->{}".format(info))
def print_name(self, name):
print("===============>>{}".format(name))
for name, fn in inspect.getmembers(AlienClass):
if isinstance(fn, types.FunctionType):
setattr(AlienClass, name, decorator(fn))
alien = AlienClass()
alien.print_info("hello world !")
alien.print_name("alien")
# The following places need to be replaced
for name, fn in inspect.getmembers(AlienClass):
if isinstance(fn, types.UnboundMethodType):
setattr(AlienClass, name, decorator(fn))