How to see the methods or attributes of an object in Python?

Asked

Viewed 7,119 times

11

Given a Python object, I can easily list which methods or attributes it has, directly in the interactive interpreter?

3 answers

9

There are a few ways to display these attributes. Considering obj being the object you want to know more about (whether it is a declared variable or just a declared class).

  • The simplest and usual is the dir:

    dir(obj)
    
  • If you want to know not only the attributes, but their current values you can also use the __dict__:

    obj.__dict__
    
  • Finally, you always have the option to consult the help:

    help(obj)
    

9


Just use the dir() function. An example of its use:

dir(objeto)

4

It is important that you know the python terminal. This will help your life a lot.

sudo apt-get install ipython.

You can install in virtualenv as well:

pip install ipython

Type ipython in the terminal.

With this you can import anything from python or your project’s class.

from people.models import Person
#digitando 'Person.' e apertando tab, você verá todos os atributos da classe Person. Veja a imagem do link

This will prevent you from doing things the "blind" and save a lot of time from your work.

http://i.stack.Imgur.com/17V56.png

Browser other questions tagged

You are not signed in. Login or sign up in order to post.