程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python foundation ----- decorator ----- correct posture of decorator used by all functions in the class

編輯:Python

List of articles

      • 1. routine
      • 2. Elegant posture
      • 3.python2 Be careful

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 !



1. routine


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】


2. Elegant posture


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")


3.python2 Be careful


# The following places need to be replaced 
for name, fn in inspect.getmembers(AlienClass):
if isinstance(fn, types.UnboundMethodType):
setattr(AlienClass, name, decorator(fn))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved