Mirage
Mirage

Reputation: 31568

How can I find python methods starting with double underscores?

I am learning python but I get confused when I see the functions or variables that start with double underscores like:

__getAttributes__ __dict

How can I find all the functions and attributes that start with double underscore so that ? can understand them better?

Upvotes: 0

Views: 280

Answers (1)

BoppreH
BoppreH

Reputation: 10173

Use the dir built- in function. It returns a list of all attributes and methods in a given object. It's also a great way to quickly discover functionality or recall method names. Example:

print dir("this is a string")

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get
slice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mo
d__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
 '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook
__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center',
 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index
', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', '
rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', '
strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Those methods are usually used by built-in functions or operators. For example __eq__ tests if two objects are equal and is used by all operators and functions that need to compare values.

There are many articles and guides out there for those "magic methods", such as http://www.rafekettler.com/magicmethods.html .

Edit: also check the comments for great official documentation on those methods. They give a nice overview of everything that is available.

Upvotes: 4

Related Questions