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.
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).
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.
>>> help('SPECIALMETHODS')
>>> help('BASICMETHODS')
>>> help('NUMBERMETHODS')
>>> help('ATTRIBUTEMETHODS')
>>> help('CALLABLEMETHODS')
>>> help('MAPPINGMETHODS')
>>> help('SEQUENCEMETHODS1')
>>> help('SEQUENCEMETHODS2')
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__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With