2010-12-13 86 views
0

我想知道是否有方法在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'] 

是否有類似的命令爲「瓦爾」或「目錄」或使會給我「X」而已?

如果不是,你們建議做什麼?走「變數」鍵並移除出現在「_x」前面的「_」?

預先感謝您!

回答

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} 
1

實例沒有屬性。他們是descriptors,所以他們必須在工作。 vars(MyClass)應該返回它。

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

print vars(MyClass).keys() 

打印

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

感謝您的快速答覆! 呃......至少我試過的例子,它返回「_x」,但我想得到「x」(莫名其妙) – BorrajaX 2010-12-13 15:08:27

+0

@BorrajaX:什麼?不,它返回'x'而不是'_x'。檢查我的例子。 – nosklo 2010-12-13 15:11:01

+0

Oooooh!我現在明白了!謝謝! – BorrajaX 2010-12-13 15:11:28

1

只是增加@ nosklo的貼什麼,因爲他的速度。

描述符是如何實現屬性。

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