本文介绍了python应用装饰器到类中的每个方法,而不检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

稍微修改,可以对类中的每个方法应用装饰器。有没有任何方法来做这个没有检查模块?我一直在试图完成这个使用元类和修改__getattribute__但我不断得到无限递归。从,可以在使用对象的正常类中修复此问题.__ getattribute __(self , 名称)。

Slightly modifying the answer from Applying python decorators to methods in a class, it is possible to apply a decorator to every method in a class. Is there any way to do this without the inspect module? I've been trying to accomplish this using metaclasses and modifying __getattribute__ but I keep getting infinite recursion. From Python - Using __getattribute__ method, this can be fixed in normal classes using object.__getattribute__(self, name). Is there anything equivalent for metaclasses?

推荐答案

定义一个元类,然后在类定义的末尾应用装饰器。 p>

Define a meta class and then just apply decorator at the end of class definition.

class Classname:
   def foo(self): pass

for name, fn in inspect.getmembers(Classname):
    if isinstance(fn, types.UnboundMethodType):
        setattr(Classname, name, decorator(fn))

对于Python 3,只需用 types.FunctionType替换 types.UnboundMethodType c $ c>

For Python 3 just replace the types.UnboundMethodType with types.FunctionType.

但是如果你真的不想使用检查比你可以这样做

but if you really don;t wanna use inspect than you can do it like this

import types

class DecoMeta(type):
   def __new__(cls, name, bases, attrs):

      for attr_name, attr_value in attrs.iteritems():
         if isinstance(attr_value, types.FunctionType):
            attrs[attr_name] = cls.deco(attr_value)

      return super(DecoMeta, cls).__new__(cls, name, bases, attrs)

   @classmethod
   def deco(cls, func):
      def wrapper(*args, **kwargs):
         print "before",func.func_name
         func(*args, **kwargs)
         print "after",func.func_name
      return wrapper

class MyKlass(object):
   __metaclass__ = DecoMeta

   def func1(self): 
      pass

MyKlass().func1()



before func1
after func1

before func1
after func1

注意:它不会装饰staticmethod和classmethod

这篇关于python应用装饰器到类中的每个方法,而不检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 14:20