How to enumerate an object's properties in Pyt

2019-01-04 21:25发布

I C# we do it through reflection. In Javascript it is simple as:

for(var propertyName in objectName)
    var currentPropertyValue = objectName[propertyName];

How to do it in Python?

6条回答
贼婆χ
2楼-- · 2019-01-04 22:06

georg scholly shorter version

print vars(theObject)
查看更多
对你真心纯属浪费
3楼-- · 2019-01-04 22:08

The __dict__ property of the object is a dictionary of all its other defined properties. Note that Python classes can override getattr and make things that look like properties but are not in__dict__. There's also the builtin functions vars() and dir() which are different in subtle ways. And __slots__ can replace __dict__ in some unusual classes.

Objects are complicated in Python. __dict__ is the right place to start for reflection-style programming. dir() is the place to start if you're hacking around in an interactive shell.

查看更多
Evening l夕情丶
4楼-- · 2019-01-04 22:13

dir() is the simple way. See here:

Guide To Python Introspection

查看更多
The star\"
5楼-- · 2019-01-04 22:14
for property, value in vars(theObject).iteritems():
    print property, ": ", value

Be aware that in some rare cases there's a __slots__ property, such classes often have no __dict__.

查看更多
We Are One
6楼-- · 2019-01-04 22:30

If you're looking for reflection of all properties, the answers above are great.

If you're simply looking to get the keys of an object, use

my_dict.keys()

my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' }
my_dict.keys() 
> ['abc', 'def', 'ghi']
查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-04 22:31

See inspect.getmembers(object[, predicate]).

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.

>>> [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']
>>> 
查看更多
登录 后发表回答