Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in Python to list the attributes and methods of a particular object?

Tags:

python

Is there a function in Python to list the attributes and methods of a particular object?

Something like:

ShowAttributes ( myObject )     -> .count    -> .size  ShowMethods ( myObject )     -> len    -> parse 
like image 615
Joan Venge Avatar asked Mar 26 '09 19:03

Joan Venge


People also ask

How can I find the methods or attributes of an object in Python?

Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.

Which function returns the list of attributes and methods in Python?

li is a list, so dir(li) returns a list of all the methods of a list.

How do you find the details of an object in Python?

In Python, you can get type information about an object with the built-in type() function. By type information I mean information about the class that implements the object. This tells you the object w1 is of type Weight. Now, you can use the type() function to check the type of anything.

Which built in function will return all the methods or attribute of an object?

You can use the built in dir() function to get a list of all the attributes a module has.


1 Answers

You want to look at the dir() function:

>>> li = [] >>> dir(li)       ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] 

li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.


Edit in response to comment:

No this will show all inherited methods as well. Consider this example:

test.py:

class Foo:     def foo(): pass  class Bar(Foo):     def bar(): pass 

Python interpreter:

>>> from test import Foo, Bar >>> dir(Foo) ['__doc__', '__module__', 'foo'] >>> dir(Bar) ['__doc__', '__module__', 'bar', 'foo'] 

You should note that Python's documentation states:

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

Therefore it's not safe to use in your code. Use vars() instead. Vars() doesn't include information about the superclasses, you'd have to collect them yourself.


If you're using dir() to find information in an interactive interpreter, consider the use of help().

like image 176
Andrew Hare Avatar answered Sep 21 '22 18:09

Andrew Hare