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 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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With