[Tutor] could somebody please explain...
Alan Gauld
alan.gauld at btinternet.com
Wed Oct 1 02:58:16 CEST 2014
On 30/09/14 23:54, Clayton Kirkwood wrote:
> I don't understand the multiplicity of some tools. Namely, why is there a
> 'a+b', operator.add(a,b), operator.__add__(a,b), operator.iadd(a,b),
> operator.__iadd__(a,b) and their related operators?
The operator module is there largely to allow you to pass
operations to functions that take functions as parameters.
For example map() which applies a function to a collection.
total = map(operator.add, [1,2,3,4,5,6])
is the same result as
total = sum([1,2,3,4,5,6])
You could do the same thing with a lambda:
total = map(lambda a,b: a+b, [1,2,3,4,5,6])
But using operator.add makes it easier to read
(and less error prone).
The operator module has functions representing most
of the builtin operations in Python.
I'm not really sure why it implements the dunder methods
(eg operatotor.__add__()) corresponding to the operations though.
I'm sure somebody else can provide a good explanation...
> Also, I found something that I can't get my mind around. It is part of the
> time/date protocols. I've not seen it anywhere else.
>
> Datetime(year=blah, blah, blah).date/time()
A Datetime object is an instance of a combined date and time.
the date and time methods return just the date or time parts
of that combined object.
> This is one of the weirder things I've run across. Is this allowed/needed in
> other functions/classes, or is it a datetime thing only?
The nearest I can think of elsewhere is the complex number
case where you can get the real/imaginary values from a
complex number
>>> n = (1+6j)
>>> n.imag
6.0
>>> n.real
1.0
But similar concepts apply in most classes where attributes,
methods or properties are used to return significant
aspects of the object. An Address might have methods to
return the city or street or house number for example.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list