0

I have created a class like this:

class test:
def __init__(self, this_uuid=uuid.uuid4().hex):
    self.this_uuid = this_uuid

When I instantiate it without parameters and print the this_uuid value like this:

t = test()
print t.this_uuid

The values I get are not random, in fact if I do it two or three times in a row spaced several seconds apart I get the same one. Can someone explain this behavior to me? If the uuid is not made in the constructor parameters it is random. This is on python 2.7.

UnitasBrooks
  • 1,062
  • 7
  • 15
  • 3
    Although not mutable in your case, the principle is the same - the default argument value is evaluated *once*, when the method is defined. And the solution is the same - set `None` as the default, and generate a UUID inside the method `if this_uuid is None:`. – jonrsharpe Jul 05 '17 at 23:19
  • Thanks, I think the most confusing part for me is that this was executed in a AWS lambda, and I was getting the same UUID each time the lambda was executed, not each time the object was instantiated. I'm still confused by that behavior, but I'll probably have to rephrase the question. – UnitasBrooks Jul 06 '17 at 16:09

0 Answers0