Home > python > Variables and functions of an object

Variables and functions of an object

Problem
You are using a library and a function returns an object. What kind of object is it? What variables does it have? What functions does it have? You would like to investigate this object you received.

Solution
I came up with the following methods:

from pprint import pprint


def print_variables_of(obj):
    """variables of an object"""
    pprint (vars(obj))


def print_callables_of(obj):
    """callables (functions too) of an object"""
    li = []
    for name in dir(obj):
        attr = getattr(obj, name)
        if hasattr(attr, '__call__'):
            li.append(name)
    pprint(li)

The first one prints the variables of an object, while the second one prints the callables (functions fall in this category) of the object.

Advertisements
Categories: python Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: