蟒蛇__getattribute__覆盖和@property装饰 [英] python __getattribute__ override and @property decorator

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

问题描述

我不得不写一个类某种类型的覆盖 __ __的ge​​tAttribute 的。
基本上我的课是一个容器,它的每个用户添加的属性保存到 self._meta 这是一本字典。

I had to write a class of some sort that overrides __getattribute__. basically my class is a container, which saves every user-added property to self._meta which is a dictionary.

class Container(object):
    def __init__(self, **kwargs):
        super(Container, self).__setattr__('_meta', OrderedDict())
        #self._meta = OrderedDict()
        super(Container, self).__setattr__('_hasattr', lambda key : key in self._meta)

        for attr, value in kwargs.iteritems():
            self._meta[attr] = value

    def __getattribute__(self, key):
        try:
            return super(Container, self).__getattribute__(key)
        except:
            if key in self._meta : return self._meta[key]
            else:
                raise AttributeError, key

    def __setattr__(self, key, value):
        self._meta[key] = value
#usage:
>>> a = Container()
>>> a
<__main__.Container object at 0x0000000002B2DA58>
>>> a.abc = 1 #set an attribute
>>> a._meta
OrderedDict([('abc', 1)]) #attribute is in ._meta dictionary

我有一些类继承其容器基类,他们的一些方法都有@property装饰。

I have some classes which inherit Container base class and some of their methods have @property decorator.

class Response(Container):
    @property
    def rawtext(self):
        if self._hasattr("value") and self.value is not None:
            _raw = self.__repr__()
            _raw += "|%s" %(self.value.encode("utf-8"))

            return _raw

问题是, .rawtext 不可访问。 (我得到AttributeError的。)._元是可访问的每一个关键,由 __ SETATTR __ <$ C $的加入每一个属性C>对象基类是访问,但方法对性能由@property装饰是没有的。我认为这与我在集装箱基类中重写 __ __的ge​​tAttribute 的方式做。我应该怎么做,使从性质 @property 访问?

problem is that .rawtext isn't accessible. (I get attributeerror.) every key in ._meta is accessible, every attributes added by __setattr__ of object base class is accessible, but method-to-properties by @property decorator isn't. I think it has to do with my way of overriding __getattribute__ in Container base class. What should I do to make properties from @property accessible?

推荐答案

我想你也许应该想想看的 __ __ GETATTR 代替的 __ __的ge​​tAttribute 在这里。所不同的是这样的: __的ge​​tAttribute __ 被inconditionally称为如果它存在 - __ GETATTR __ 只调用如果Python不能找到通过其他手段的属性

I think you should probably think about looking at __getattr__ instead of __getattribute__ here. The difference is this: __getattribute__ is called inconditionally if it exists -- __getattr__ is only called if python can't find the attribute via other means.

这篇关于蟒蛇__getattribute__覆盖和@property装饰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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