首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >类中的Python装饰器

类中的Python装饰器
EN

Stack Overflow用户
提问于 2009-08-11 23:01:45
回答 8查看 144K关注 0票数 183

可以这样写吗:

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

    @self._decorator
    def bar(self):
        pass

失败:@self中的self未知

我也试过了:

@Test._decorator(self)

这也失败了:测试未知

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

EN

回答 8

Stack Overflow用户

发布于 2016-11-17 20:48:55

import functools


class Example:

    def wrapper(func):
        @functools.wraps(func)
        def wrap(self, *args, **kwargs):
            print("inside wrap")
            return func(self, *args, **kwargs)
        return wrap

    @wrapper
    def method(self):
        print("METHOD")

    wrapper = staticmethod(wrapper)


e = Example()
e.method()
票数 30
EN

Stack Overflow用户

发布于 2016-06-07 17:43:25

这是从定义在同一个类中的decorator内部访问(并使用) self的一种方法:

class Thing(object):
    def __init__(self, name):
        self.name = name

    def debug_name(function):
        def debug_wrapper(*args):
            self = args[0]
            print 'self.name = ' + self.name
            print 'running function {}()'.format(function.__name__)
            function(*args)
            print 'self.name = ' + self.name
        return debug_wrapper

    @debug_name
    def set_name(self, new_name):
        self.name = new_name

输出(在Python 2.7.10上测试):

>>> a = Thing('A')
>>> a.name
'A'
>>> a.set_name('B')
self.name = A
running function set_name()
self.name = B
>>> a.name
'B'

上面的例子是愚蠢的,但它是有效的。

票数 12
EN

Stack Overflow用户

发布于 2012-01-18 01:48:26

我在研究一个非常相似的问题时发现了这个问题。我的解决方案是将问题分成两部分。首先,您需要捕获要与类方法关联的数据。在这种情况下,handler_for会将Unix命令与该命令输出的处理程序相关联。

class OutputAnalysis(object):
    "analyze the output of diagnostic commands"
    def handler_for(name):
        "decorator to associate a function with a command"
        def wrapper(func):
            func.handler_for = name
            return func
        return wrapper
    # associate mount_p with 'mount_-p.txt'
    @handler_for('mount -p')
    def mount_p(self, slurped):
        pass

现在我们已经将一些数据与每个类方法相关联,我们需要收集这些数据并将其存储在一个class属性中。

OutputAnalysis.cmd_handler = {}
for value in OutputAnalysis.__dict__.itervalues():
    try:
        OutputAnalysis.cmd_handler[value.handler_for] = value
    except AttributeError:
        pass
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1263451

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档