Why can't date and regexes in Python be as succinct as they are in JS? [closed]
- Why is
datetime
a "child" of itself? Why is itdatetime.datet开发者_如何学JAVAime.now
instead ofdatetime.now
? - Why can't I use regex literals like in Javascript? EG
/foo/.test('foo')
datetime is a python module
that contains datetime class
that has a method now
.
I agree with you datetime.datetime only looks ugly because the module and class have the same name . I have myself been stumped at times due to this specific issue.
I have mostly incorporated the class directly in my module by doing.
from datetime import datetime <-- the first datetime is module and second a class
....
datetime.now() <------ this datetime is a class
datetime.now()
(wheredatetime
is a class and.now()
is a static method of this class) is perfectly possible. You just have tofrom datetime import datetime
(where the firstdatetime
is a module of the standard library -- python likes namespaces very much -- and the second the said class in that module). It's just not common.Design decision. I suppose it complicates the grammar quite a bit (it sure looks like it does) and it's also not clearly superior - forward slashes must be escaped, the alternatuve (raw string literals) don't need backslashe escaping, so they're about even. Also, Python (unlike e.g. Perl, where regex literals come from as far as I know) is not solely a scripting language for e.g. text processing. I've written several Python modules a hundred lines long that didn't use a single regex.
For 1. you could do this:
from datetime import datetime
datetime.now() #thus saving "datetime"
Because it's a namespace. You can change that
[~]
|4>from datetime import datetime
[~]
|5>givemethetime = datetime.now
[~]
|6>givemethetime()
[6] datetime.datetime(2010, 12, 10, 12, 27, 20, 872721)
Javascript has some great strengths, but namespaces aren't really seen as one of its strengths (there are workarounds as mentioned in the book: Javascript: the good parts).
As mentioned by others, isn't date succinct if you do: from datetime import datetime?
精彩评论