import module == from module import *?

后端 未结 3 1964
自闭症患者
自闭症患者 2021-01-16 12:06

I had a problem with the Django tutorial so I asked a question here. No-one knew the answer, but I eventually figured it out with help from Robert. Python seems to be trea

相关标签:
3条回答
  • 2021-01-16 12:46

    The problem in the latter snippet is with this part of your code:

    return (self.pub_date() == datetime.date.today())
    

    self.pub_date contains a datetime.datetime instance. It's not callable like that. For example:

    >>> import datetime
    >>> d = datetime.datetime.now()
    >>> d()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'datetime.datetime' object is not callable
    >>>
    

    If you want to compare only the date, you should call it thus:

    return (self.pub_date.date() == datetime.date.today())
    
    0 讨论(0)
  • 2021-01-16 12:50

    As we discussed in the comments, the problem is not with the code, but the way you are updating the source. python caches modules in sys.modules. You can reload individual modules using the reload function, but for many changes it's best to reload the entire shell. In many cases it looked as though the changes had propagated because the error messages seemed to have changed, this is because python doesn't cache the source code of the file, so when it references code, it shows you the newest version. Hopefully now, you can apply the other answers with more success.

    0 讨论(0)
  • 2021-01-16 12:57

    "My question is: Why is datetime in my namespace without me using from datetime import *."

    Because you did import datetime. Then you have datetime in your namespace. Not the CLASS datetime, but the MODULE.

    Python does not treat import datetime the same way as from datetime import *. Stop asking why it does that, when it does not.

    >>> import datetime
    >>> date.today()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'date' is not defined
    >>> 
    

    There is something else happening. If it's Django magic or not, I don't know. I don't have a Django installation where I can try this at the moment. (If there is a super-quick way of making that happen, tell me. easy_installing Django wasn't enough. :) )

    0 讨论(0)
提交回复
热议问题