Python Decorator访问自我

时间:2015-10-26 17:32:35

标签: python python-decorators

这是一个Python类中的示例方法:

def publish_aggregate_account_group_stats(self, account_group_token):
    message = {
        "type": "metrics-aggregate-account-group-stats",
        "accountGroupToken": account_group_token
    }
    try:
        self._get_writer().write(message)
    except:
        self._put_cache(message)

我的班级中有一些方法都运行try/except,我认为可以通过简单地创建一个装饰器来清理或清理它,为我处理。我只是不确定装饰器的外观/工作方式是访问self

1 个答案:

答案 0 :(得分:1)

这样的事情会起作用:

from contextlib import contextmanager
class Test(object):
    def __init__(self):
        self.j = set()

    @contextmanager
    def handle_exc(self, msg):
        try:
            yield
        except:
            print('adding to internal structure:', msg)
            self.j.add(msg)

    def test(self):
        m = 'snth'
        with self.handle_exc(m):
            raise Exception('error')

装饰器很难在这里使用,因为你在函数本身内创建了值,所以外部装饰者永远不会知道它们,除非你找到一种方法来传播它们(通过某种例外或某种东西。)

相关问题