类中的 Python 装饰器

标签 python class decorator self

可以写这样的东西:

class Test(object):
    def _decorator(self, foo):
        foo()

    @self._decorator
    def bar(self):
        pass

失败:@self 中的 self 未知

我也尝试过:

@Test._decorator(self)

也失败了:测试未知

我想暂时更改一些实例变量 在装饰器中,然后运行装饰方法,之前 将它们改回来。

最佳答案

这样的东西可以满足您的需要吗?

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

test = Test()

test.bar()

这避免了调用 self 来访问装饰器,并将其作为常规方法隐藏在类命名空间中。

>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>> 
<小时/>

编辑回答评论中的问题:

如何在另一个类中使用隐藏的装饰器

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

    _decorator = staticmethod( _decorator )

class TestB( Test ):
    @Test._decorator
    def bar( self ):
        print "override bar in"
        super( TestB, self ).bar()
        print "override bar out"

print "Normal:"
test = Test()
test.bar()
print

print "Inherited:"
b = TestB()
b.bar()
print

输出:

Normal:
start magic
normal call
end magic

Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic

关于类中的 Python 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951157/

相关文章:

Javascript:如何在不同类之间进行通信?

java - 使用装饰器模式时找到特定类型的装饰器?

c# - 装饰者模式 - 向接口(interface)添加方法

python - 带参数的装饰器

python - 为特定版本的 Python 编译 Python 模块

python - 如何在 django 中暂时禁用外键约束

c++ - 检查对象是否是带有模板的类的实例

c++ - 高效分组重叠矩形

python - 在 matplotlib basemap 正射投影中更改图像背景颜色

javascript更改css类,而不是 append 到它