A constructor for dataclasses with randomized attribute values

Question:

Hi could someone explain whats happening here:
i want to instantiate objects with random values.

@dataclass
class Particle:
    pos = (random.randint(0, 800), random.randint(0, 800))

for _ in range(3):
    p = Particle()
    print(p.pos)

prints:

  • (123, 586)
  • (123, 586)
  • (123, 586)

expected behaviour wold be three tuples with different values. Whats happening here??

(when i use a normal class it works as expected)

Asked By: user14534957

||

Answers:

You are creating the random integers only once at class definition. What you want is a default factory for your value.

See https://docs.python.org/3/library/dataclasses.html#dataclasses.field for more details.

Example:

def rndints():
    return (random.randint(0, 800), random.randint(0, 800))

@dataclass
class Particle:
    pos = field(default_factory=rndints)
Answered By: Carlos Horn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.