I want a Class attribute which sets datetime.now() when the a new instance of the class is instantiated. With this code, MyThing.created seems to always be when MyThing is imported, as opposed to when mt is instantiated.
from datetime import datetime
class MyThing:
__init__(self, created=datetime.now()):
self.created = created
MyThing.created
datetime.datetime(2012, 7, 5, 10, 54, 24, 865791)
mt = MyThing()
mt.created
datetime.datetime(2012, 7, 5, 10, 54, 24, 865791)
How can I do it so that created is when mt is instantiated, as opposed to MyThing?
Default values for function parameters are computed once, when the function is defined. They are not re-evaluated when the function is called. Typically, you’d use
Noneas the default value, and test for it in the body:Even better, it looks like maybe you don’t want to ever pass a created date into the constructor, in which case: