具有随机属性值的数据类的构造函数

use*_*957 2 python python-dataclasses

您好,有人可以解释一下这里发生的事情:我想用随机值实例化对象。

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

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

Run Code Online (Sandbox Code Playgroud)

印刷:

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

预期的行为将是具有不同值的三个元组。这里发生了什么事??

(当我使用普通类时,它按预期工作)

Car*_*orn 7

您仅在类定义时创建一次随机整数。您想要的是您的值的默认工厂。

有关更多详细信息,请参阅https://docs.python.org/3/library/dataclasses.html#dataclasses.field 。

例子:

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

@dataclass
class Particle:
    pos = field(default_factory=rndints)
Run Code Online (Sandbox Code Playgroud)