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)
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)
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)
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)