0

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.

0

5 Answers 5

3

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])
Sign up to request clarification or add additional context in comments.

Comments

2

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

dir(info) will provide attribute names, OP is asking for values of attributes.
Ya. I didn't notice it @sidi. You are right. We can use vars(info) or info.__dict__ as sidi mentioned.
2

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

@Wessie dir(info) would only list the attribute names, OP here is asking for values of attributes.
I get the idea of avoiding to access private attributes. Hence vars(info).
1

You can just use dir():

dir(info)

dir() man:

With an argument, attempt to return a list of valid attributes for that object.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.