开发者

Why can't date and regexes in Python be as succinct as they are in JS? [closed]

开发者 https://www.devze.com 2023-01-30 13:14 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.
  1. Why is datetime a "child" of itself? Why is it datetime.datet开发者_如何学JAVAime.now instead of datetime.now?
  2. 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


  1. datetime.now() (where datetime is a class and .now() is a static method of this class) is perfectly possible. You just have to from datetime import datetime (where the first datetime 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.

  2. 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消