[Tutor] could somebody please explain...
Steven D'Aprano
steve at pearwood.info
Wed Oct 1 04:33:57 CEST 2014
On Tue, Sep 30, 2014 at 03:54:42PM -0700, Clayton Kirkwood wrote:
> 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()
>
> datetime(2013,3,6).date() #returns.
> datetime.date(2013,3,6)
>
> datetime(2013,3,6).time() #returns.
> datetime.time(0,0)
>
> 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?
I'm afraid I have no clue what part of this you consider weird. Is it
that the date() and time() methods don't take an argument? That's quite
common:
py> "Hello".upper()
'Hello'
Or is it that the result of calling date() or time() methods isn't the
same type of thing as what you started with? Again, that's very common:
py> {1: 'a', 2: 'b'}.keys() # Start with a dict, returns a list.
[1, 2]
Start with a datetime object. The date() method returns the date part
alone, so it returns a date object. The time() method returns the time
part alone, so it returns a time object.
Or maybe you're weirded out by the leading "datetime" in the name.
That's unfortunate, but not weird. The datetime module contains at least
three classes. When you print the class, they show the module name. It
is unfortunate that the module name happens to have the same name as one
of those classes:
py> datetime
<module 'datetime' from '/usr/local/lib/python2.7/lib-dynload/datetime.so'>
py> datetime.date
<type 'datetime.date'>
py> datetime.time
<type 'datetime.time'>
py> datetime.datetime
<type 'datetime.datetime'>
So when you see something like this:
py> d = datetime.datetime(2000, 5, 22, 11, 5, 27)
py> d
datetime.datetime(2000, 5, 22, 11, 5, 27)
the "datetime." means the module, and the "datetime(...)" means the
class with its various arguments.
Is this common? Sadly, there are quite a few modules where the main
function or class in the module has the same, or very similar, name:
dis.dis
bisect.bisect
decimal.Decimal
fractions.Fraction
etc.
(P.S. it is better to raise each independent question in a separate
email.)
--
Steven
More information about the Tutor
mailing list