How to enumerate an object's properties in Python?
我们是通过思考来做到的。在javascript中,它很简单:
1 2 | for(var propertyName in objectName) var currentPropertyValue = objectName[propertyName]; |
如何在python中完成?
1 2 | for property, value in vars(theObject).iteritems(): print property,":", value |
请注意,在某些罕见的情况下,有一个
见
Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.
1 2 3 4 5 6 7 8 9 | >>> [name for name,thing in inspect.getmembers([])] ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> |
Python自省指南
对象的
对象在Python中很复杂。
如果你在寻找所有属性的反射,上面的答案是很好的。
如果您只是想获取对象的键,请使用
1 2 3 | my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' } my_dict.keys() > ['abc', 'def', 'ghi'] |
Georg Scholly较短版本
1 | print vars(theObject) |