Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I look inside a Python object?

I'm starting to code in various projects using Python (including Django web development and Panda3D game development).

To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties.

So say I have a Python object, what would I need to print out its contents? Is that even possible?

like image 707
littlejim84 Avatar asked Jun 17 '09 10:06

littlejim84


People also ask

How do you print the contents of an object in Python?

Print an Object in Python Using the __repr__() Method When we print an object in Python using the print() function, the object's __str__() method is called. If it is not defined then the __str__() returns the return value of the __repr__() method.

How do you check inside a class in Python?

There is the dir(theobject) method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """). Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only methods.


2 Answers

Python has a strong set of introspection features.

Take a look at the following built-in functions:

  • type()
  • dir()
  • id()
  • getattr()
  • hasattr()
  • globals()
  • locals()
  • callable()

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

like image 191
Brandon E Taylor Avatar answered Oct 18 '22 02:10

Brandon E Taylor


object.__dict__

like image 45
mtasic85 Avatar answered Oct 18 '22 02:10

mtasic85