在@property之后装饰类方法 [英] Decorating a class method after @property

查看:62
本文介绍了在@property之后装饰类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用装饰器包装除__init__之外的各种对象的所有方法.

I want to wrap every method of various objects except __init__ using a decorator.

class MyObject(object):

    def method(self):
        print "method called on %s" % str(self)

    @property
    def result(self):
        return "Some derived property"

def my_decorator(func):
    def _wrapped(*args, **kwargs):
        print "Calling decorated function %s" % func
        return func(*args, **kwargs)
    return _wrapped


class WrappedObject(object):

    def __init__(self, cls):
        for attr, item in cls.__dict__.items():
            if attr != '__init__' and (callable(item) or isinstance(item, property)):
                setattr(cls, attr, my_decorator(item))
        self._cls = cls

    def __call__(self, *args, **kwargs):
        return self._cls(*args, **kwargs)

inst = WrappedObject(MyObject)()

但是,属性实例结果的包装与此等效:

However, the wrapping of a property instance results is equivalent to this:

@my_decorator
@property
def result(self):
    return "Some derived property"

当所需结果等于此值时:

When the desired result is something equivalent to this:

@property
@my_decorator
def result(self):
    return "Some derived property"

似乎属性对象的属性是只读的,从而阻止了在属性包装后修改函数.我对已经需要的黑客级别不太满意,无论如何我还是不想深入研究该属性对象.

It seems the attributes of a property object are read-only preventing modifying the function after property has wrapped it. I'm not too comfortable with the level of hackery required already and I'd rather not delve into the property object anyway.

我能看到的唯一其他解决方案是即时生成一个我希望避免的元类.我缺少明显的东西吗?

The only other solution I can see is to generate a metaclass on the fly which I was hoping to avoid. Am I missing something obvious?

推荐答案

此示例中还有其他一些问题,但有一个疑问,您需要做的所有事情 是,当您包装属性时

There are a few other issues in this sample, but to atain to question, all you have to do is, when you are wrapping a property

包装属性时,请包装其__get__方法:

When you are wrapping a property, wrap its __get__ method instead:

class MyObject(object):

    def method(self):
        print "method called on %s" % str(self)

    @property
    def result(self):
        return "Some derived property"

    def common(self, a=None):
        print self

def my_decorator(func):
    def _wrapped(*args, **kwargs):
        print "Calling decorated function %s" % func
        return func(*args, **kwargs)
    return _wrapped


class WrappedObject(object):

    def __init__(self, cls):
        for attr, item in cls.__dict__.items():
            if attr != '__init__' and callable(item):
                setattr(cls, attr, my_decorator(item))
            elif  isinstance(item, property):
                new_property = property(my_decorator(item.__get__), item.__set__, item.__delattr__)
                setattr(cls, attr, new_property)
        self._cls = cls

    def __call__(self, *args, **kwargs):
        return self._cls(*args, **kwargs)

inst = WrappedObject(MyObject)()

那是对完成任务的代码的简单修改. 但是,为了避免重写其属性,我将其更改为包装的类的子类.您可以通过编程简单地创建带有名称的子类,带有基数的元组和以dict作为参数的子类.

That is the simpelst modification to your code that does the job. I'd however change it to dinamically a subclass of the classs it is wrapping, in order to avoid re-writing its attributes. You can create a subclass programtically by simply caling type with the name, a tuple withe the bases, and a dict as parameters.

实际上,子类化给定类几乎不需要修改给定代码, 但对于我指示的type通话.我刚刚在这里进行了测试-将WrappedObject类更改为:

Actually, subclassing the given class requires almost no modification on the given code, but for the type call I indicated. I just tested it here - change your WrappedObject class to:

class WrappedObject(object):

    def __init__(self, cls):
        dct = cls.__dict__.copy()
        for attr, item in dct.items():
            if attr != '__init__' and callable(item):
                dct[attr] =  my_decorator(item)
            elif  isinstance(item, property):
                new_property = property(my_decorator(item.__get__), item.__set__, item.__delattr__)
                dct[attr] = new_property
        self._cls = type("wrapped_" + cls.__name__, (cls,), dct)

    def __call__(self, *args, **kwargs):
        return self._cls(*args, **kwargs)

这篇关于在@property之后装饰类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆