Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewing a list of all python operators via the interpreter

Say I've just implemented some class in Python and want to overload say the '-' operator, but can't remember if I need to use __subtract__, __minus__, or in fact the correct answer __sub__. Is there a quick way to find this out via the interpreter? I tried simple things like help(-) but no success.

There's plenty of online resources to give the definitive list of available operators, but I'm looking for a quick offline method.

For common operators one quickly memorizes them, but some lesser used ones often need looking up.

like image 211
Bogdanovist Avatar asked Aug 22 '13 22:08

Bogdanovist


People also ask

What is the interpreter of Python?

The Python interpreter is a virtual machine, meaning that it is software that emulates a physical computer. This particular virtual machine is a stack machine: it manipulates several stacks to perform its operations (as contrasted with a register machine, which writes to and reads from particular memory locations).

What does the & Do in Python?

and is a Logical AND that returns True if both the operands are true whereas '&' is a bitwise operator in Python that acts on bits and performs bit by bit operation. Note: When an integer value is 0, it is considered as False otherwise True when using logically.


2 Answers

All standard operators

>>> help('SPECIALMETHODS')

Only basic ones

>>> help('BASICMETHODS')

Only numeric ones

>>> help('NUMBERMETHODS')

Other help subsections

>>> help('ATTRIBUTEMETHODS')
>>> help('CALLABLEMETHODS')
>>> help('MAPPINGMETHODS')
>>> help('SEQUENCEMETHODS1')
>>> help('SEQUENCEMETHODS2')
like image 81
Vanni Totaro Avatar answered Oct 30 '22 23:10

Vanni Totaro


Use dir(obj), that will list all attributes of the object (or class) obj. For example you know that you can add integers so type

>>> dir(int) # using the class int (or type in this case) here
    ['__abs__',
 '__add__',
 '__and__',
 '__class__',
 '__cmp__',
 ...

or for formatted output

>>> print '\n'.join(dir(1)) # using an instance of int here
__abs__
__add__
__and__
__class__
__cmp__
...

then you can get more information via

>>> help(int.__add__)
like image 39
dastrobu Avatar answered Oct 31 '22 00:10

dastrobu