我想知道是否有方法在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」前面的「_」?
預先感謝您!
感謝您的快速答覆! 呃......至少我試過的例子,它返回「_x」,但我想得到「x」(莫名其妙) – BorrajaX 2010-12-13 15:08:27
@BorrajaX:什麼?不,它返回'x'而不是'_x'。檢查我的例子。 – nosklo 2010-12-13 15:11:01
Oooooh!我現在明白了!謝謝! – BorrajaX 2010-12-13 15:11:28