Python class with datetime.now () when instantiating

I need a Class attribute that sets datetime.now() when instantiating a new instance of the class. With this code, MyThing.created seems to always be when MyThing imported, and not when mt is created.

 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 this so that created created by mt and not MyThing ?

+4
source share
2 answers

The default values โ€‹โ€‹for function parameters are calculated once when the function is defined. They are not overestimated when a function is called. Typically, you use None as the default and check it in the body:

 def __init__(self, created=None): self.created = created or datetime.now() 

Even better, it looks like you don't want to ever pass the created date to the constructor, in which case:

 def __init__(self): self.created = datetime.now() 
+6
source

Do not set it in parameters, since they are members of the function itself, since everything is an object of the first class.

 class MyThing: __init__(self, created=None): self.created = created if created is None: self.created = datetime.now() 
+4
source

All Articles