Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class with datetime.now() when instantiated

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?

like image 314
MFB Avatar asked Jul 05 '12 00:07

MFB


2 Answers

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 None as the default value, and test for it in the body:

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

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

def __init__(self):
    self.created = datetime.now()
like image 72
Ned Batchelder Avatar answered Sep 23 '22 10:09

Ned Batchelder


Don't set it in the parameters as they are members of the function itself since everything is a first class object.

class MyThing:
    __init__(self, created=None):
        self.created = created
        if created is None:
            self.created = datetime.now()
like image 22
jamylak Avatar answered Sep 22 '22 10:09

jamylak