Is there any method to let me know the values of an object's attributes?
For example, info = urllib2.urlopen('http://www.python.org/')
I wanna know all the attributes' values of info. Maybe I don't know what are the attributes the info has. And str() or list() can not give me the answer.
5 Answers
To get all the names of object's attributes, use dir(obj). To get their values, use getattr(obj, attr_name). You could print all the attributes and their values like so:
for attr in dir(obj):
print(attr, getattr(obj, attr))
If you don't need the built-in attributes, such as __str__ etc, you can simply use obj.__dict__, which returns a dictionary of object's attributes and their values.
for k in obj.__dict__:
print(k, obj.__dict__[k])
Comments
You can use Python's dir(). dir(info) will return all the valid attributes for the object info.
info = urllib2.urlopen('http://www.python.org/')
print dir(info)
2 Comments
You can use vars(info) or info.__dict__. It will return the object's namespace as a dictionary in the attribute_name:value format.
2 Comments
dir(info) would only list the attribute names, OP here is asking for values of attributes.vars(info).You can just use dir():
dir(info)
With an argument, attempt to return a list of valid attributes for that object.
Comments
All methods using dir() or looking at dict are bascially a no go.
Better check
obj.__class__
and
obj.__class__.__bases__
in order to get an idea what the object really is.
Then you should check the offial API documentation of the module.
Methods and data might be private and are in general not for public consumption unless stated otherwise by the documentation.