【发布时间】: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