operator module functions

marco.nawijn at colosso.nl marco.nawijn at colosso.nl
Wed Oct 8 04:46:02 EDT 2014


For me it makes sense. operator.add should be used in a "global" context
(I don't know how to express it otherwise). So you provide it with the 
two values that you want to add. The .__add__ variants are bound to a
particular instance and you provide it with a single value that you want
to add. 

You also need the dunder versions when you want to implement addition for
user defined types. So although they are similar, I do believe they have
slightly different uses. As an example, you cannot use the dunder versions
for literals.

>> 2.__add__(3) # Oops, does not work
>> a = 2
>> a.__add__(3)
5
>> import operator
>> operator.add(2,3) # Fine

I also think operator.add versus .__add__ is equivalent to the global
getattr() and .__getattr__.

Marco







More information about the Python-list mailing list