仅获取实例的属性

Bor*_*jaX 0 python properties decorator

我想知道Python(2.6)中是否有一种方法只能获得实例所具有的属性的名称.

比方说我有:

#!/usr/bin/python2.6

class MyClass(object):
    def __init__(self):   
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        print "Setting x to %s" % (value)
        try:
            self._x = int(value)
        except ValueError:
            self._x = None



#main (test area)
if __name__ == '__main__':
    a = MyClass()
    a.x = "5"
    print str(a.x)
    print "Vars: %s" %vars(a)   
    print "Dir: %s" %dir(a)
Run Code Online (Sandbox Code Playgroud)

哪个输出:

Vars: {'_x': 5}
Dir: ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_x', 'x']
Run Code Online (Sandbox Code Playgroud)

是否有类似"vars"或"dir"的命令,只会给我"x"?

如果没有,你们建议做什么?走"vars"键并删除"_x"前面出现的"_"?

先感谢您!

Syl*_*sne 5

您可以使用以下代码:

def iter_properties_of_class(cls):
    for varname in vars(cls):
        value = getattr(cls, varname)
        if isinstance(value, property):
            yield varname

def properties(inst):
    result = {}
    for cls in inst.__class__.mro():
        for varname in iter_properties_of_class(cls):
            result[varname] = getattr(inst, varname)
    return result

>>> a = MyClass()
>>> a.x = 5
Setting x to 5
>>> properties(a)
{'x': 5}
Run Code Online (Sandbox Code Playgroud)