python dictmixin对象与属性装饰器

时间:2012-12-06 19:04:03

标签: python properties dictmixin

我被指示使用更多的python方式的setter和getters @property。所以我们有这样的事情:

from UserDict import DictMixin

class A(dict):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value

    def __getitem__(self, key):
        return getattr(self, key)

    def __setitem__(self, key, value):
        setattr(self, key, value)

    def keys(self):
        return [k for k in self.__dict__.keys() if not k.startswith('_')]

    def do_whatever(self):
        pass


a = A(1,2)
print a.keys()

输出是['b'],起初我没想到,但它确实有意义。

问题是如何获取所有属性名称而不是方法名称。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

属性实现为descriptors,因此属于,而不属于实例

>>> class Question(object):
...     @property
...     def answer(self):
...         return 7 * 6
... 
>>> q = Question()
>>> q.answer
42
>>> q.__dict__
{}
>>> for key, value in Question.__dict__.iteritems():
...     if isinstance(value, property):
...         print key
...
answer