time() function is returning the same value every time

Asked

Viewed 29 times

0

I have the following code snippet:

from time import time

class Transaction:
    def __init__(self, value, timestamp=time()):
        self.value = value
        self.created_at = timestamp

Creating an instance and seeing your timestamp:

t1 = Transaction()
t1.created_at
'1554492682.907307'

Now creating a second instance and also seeing your timestamp:

t2 = Transaction()
t2.created_at
'1554492682.907307'

Note that the timestamp of the object t2 is the same as the object of the object t1 and were not created at the same time logically.

Why the argument that has a default value is being calculated only once and repeating for all subsequent objects?

  • Same old scheme: any doubt just ask. If you disagree that it is duplicated let me know that we reevaluate the closure.

  • @Andersoncarloswoss In the answer you have marked it says that this behavior occurs for only mutable types like "dictionaries, lists, etc". In my doubt, the created_at attribute is float type, but float is not immutable?

  • 1

    The idea is: the default value of the argument is defined at the time of class definition, that is, its function time will be called only once and will use the return as default value.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.