Object introspection
Object introspection
Introspection: the ability to determine the type of an object at runtime.
One of Python’s strengths.
Everything in Python is an object and we can examine those objects.
dir
dirReturns a list of attributes and methods belonging to an object. Here is an example:
my_list = [1, 2, 3]
dir(my_list)
# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
# '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
# '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
# '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
# '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
# '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
# 'remove', 'reverse', 'sort']Introspection gave us the names of all the methods of a list.
dir() without any argument then it returns all names in the current scope.
type and id
type and idtype function returns the type of an object.
Example:
id returns the unique ids of various objects.
Example:
inspect module
inspect moduleProvides several useful functions to get information about live objects.
Example: check the members of an object by running:
Last updated