Reputation: 125
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.
Upvotes: 0
Views: 463
Reputation:
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.
Upvotes: 0
Reputation:
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])
Upvotes: 3
Reputation: 2257
You can use vars(info)
or info.__dict__
. It will return the object's namespace as a dictionary in the attribute_name:value format.
Upvotes: 2
Reputation: 4391
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)
Upvotes: 2