仅获取实例的属性

0 投票
3 回答
1797 浏览
提问于 2025-04-16 08:28

我在想,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)

这段代码的输出是:

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']

有没有类似于“vars”或“dir”的命令,可以让我只得到“x”这个属性?

如果没有,你们有什么建议?是遍历“vars”的键,然后把前面的“_”去掉吗?

提前谢谢大家!

3 个回答

1

实例是没有属性的。它们是一些叫做描述符的东西,所以这些描述符必须在里面才能正常工作。使用vars(MyClass)这个命令应该能返回它们。

class MyClass(object):
    @property
    def x(self):
        pass

print vars(MyClass).keys()

打印输出

['__module__', '__dict__', 'x', '__weakref__', '__doc__']
1

我只是想补充一下@nosklo说的内容,感谢他的快速回复。

描述符就是用来实现属性的方式。

>>> o = MyClass()
>>> print type(o.x)
<type 'NoneType'>
>>> print type(MyClass.x)
<type 'property'>
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}

撰写回答