【问题标题】:Get only properties of an instance仅获取实例的属性
【发布时间】:2010-12-13 15:03:46
【问题描述】:

我想知道 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”键,去掉“_x”前面出现的“_”?

提前谢谢你!

【问题讨论】:

    标签: python properties decorator


    【解决方案1】:

    您可以使用以下代码:

    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}
    

    【讨论】:

      【解决方案2】:

      实例没有属性。他们是descriptors,所以他们必须在class中才能工作。 vars(MyClass) 应该返回它。

      class MyClass(object):
          @property
          def x(self):
              pass
      
      print vars(MyClass).keys()
      

      打印

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

      【讨论】:

      • 感谢您的快速回答!嗯......至少我试过的例子,它返回“_x”,但我想得到“x”(不知何故)
      • @BorrajaX:什么?不,它返回 x 而不是 _x。检查我的例子。
      • 噢噢噢!我现在明白了!谢谢!
      【解决方案3】:

      只是添加到 @nosklo 发布的内容中,因为他的速度很快。

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

      >>> o = MyClass()
      >>> print type(o.x)
      <type 'NoneType'>
      >>> print type(MyClass.x)
      <type 'property'>
      

      【讨论】:

        猜你喜欢
        • 2019-02-07
        • 2011-08-03
        • 1970-01-01
        • 1970-01-01
        • 2017-04-18
        • 1970-01-01
        • 2019-02-01
        • 1970-01-01
        • 2018-06-21
        相关资源
        最近更新 更多