python - 让装饰器调用类中特定于方法的 pre 和 post 方法

标签 python decorator introspection python-decorators

在 python 3 中,我有一个基类,从中派生出一个类:

class Base:
    # Tell the Base class to look and for pre/post 
    # functions the same name, and call them
    def f(self):
        print("f()")

    def no_prepost(self): # should work, too
        print("nothing")

class Derived(Base):
    def pre_f(self):
        print("pre_f()")

    def post_f(self):
        print("post_f()")

我想调用 pre/post 方法(如果存在),但不始终明确说明它们:

foo = Derived()

# if exists: foo.pre_f() -- too verbose, do this automatically!
foo.f()
# if exists: foo.post_f()

最佳答案

装饰器函数和一些类自省(introspection)可以做到这一点。如果找到匹配的函数,则使用相同的参数调用它:

def prepost(f):
    def prepost_wrapper(self, *args, **kwargs):
        pre_name  = 'pre_'  + f.__name__
        post_name = 'post_' + f.__name__
        if hasattr(self, pre_name):  getattr(self, pre_name) (*args, **kwargs)
        ret = f(self, *args, **kwargs)
        if hasattr(self, post_name): getattr(self, post_name)(*args, **kwargs)
        return ret
    return prepost_wrapper

class Base:
    @prepost    
    def f(self, a, b=99):
        print("f()", a, b)
    @prepost
    def missing(self):
        print("nothing special here")

class Derived(Base):
    def pre_f(self, a, b=0): # the arguments must match!
        print("pre_f()", a, b)
    def post_f(self, a, b=1):
        print("post_f()", a, b)

foo = Derived()
foo.f("abc")
foo.missing()
foo.f("xyz", 12)

输出:

pre_f() abc 0
f() abc 99
post_f() abc 1
nothing special here
pre_f() xyz 12
f() xyz 12
post_f() xyz 12

关于python - 让装饰器调用类中特定于方法的 pre 和 post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32058100/

相关文章:

python 2.6.6 "phantom"空格

python - Py2Exe: "error: invalid command: py2exe"

python - 克服空数组的 ValueError

python - 如何使类装饰器不破坏 isinstance 函数?

javascript - 通过类装饰器自动将类添加到列表?

c# - 动态确定调用哪个静态方法

python 到 MATLAB 代码、数字列表和求和

Decorator 和 decorated 类在不同的 bean archives 中

Java 自省(introspection) - 奇怪的行为

perl - 确定 Moose 属性和方法是从哪里继承的?