在 python 中,如何多次调用 class 并使 randint 随机?

In python, how do I call a class multiple times and have randint be random?

在Python中,我试图用一个class和一个随机整数作为健康值来制作一个角色,但每次的结果都是一样的。

class Player():
    life = randint(25,30)
    maxhealth = life
    attack = 5
    name = ""
    ......

我创建播放器的方法是这样的:

playernum = -1
while playernum < 1:
    playernum = int(input("How many players? "))
players = []
for x in range(playernum):
    print("Player " + str(x+1))
    players.append(Player())

我如何更改它以便我创建的每个玩家的健康值都不同?

您应该使用实例属性:

class Player():
    def __init__(self):
        self.life = randint(25,30)
        self.maxhealth = self.life
        self.attack = 5
        self.name = ""

您目前有 class 个只评估一次的属性。在你的 class 中添加一个打印,你会看到 "here" 只出现一次:

class Player():
    print("here")
    life = randint(25,30)
    maxhealth = life
    attack = 5
    name = ""

如果您在 init 方法中执行相同的操作,您将在每次创建实例时看到输出:

class Player():
    def __init__(self):
        print("here")

__init__:

class Player():

    def __init__(self):
        self.life = randint(25,30)
        self.maxhealth = life
        self.attack = 5
        self.name = ""
        ......

另见 this question and its answers