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?
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?
georg scholly shorter version
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 functionsvars()
anddir()
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.dir()
is the simple way. See here:Guide To Python Introspection
Be aware that in some rare cases there's a
__slots__
property, such classes often have no__dict__
.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()
See
inspect.getmembers(object[, predicate])
.