Python 如何在类中的函数中生成不重复的随机数?

Python 如何在类中的函数中生成不重复的随机数?,python,Python,函数中的随机数保持原样,例如,当数为1时,它保持为1。但当它被带到函数之外时,它会生成其他数字 如何在函数中生成不重复的随机数 from random import * randomEnemyNames = ["Gandalf", "Batman", "Magikarp", "Ed Sheeran", "Justin Bieber"] class Character(object): def __init__(self, name): self.name = name

函数中的随机数保持原样,例如,当数为1时,它保持为1。但当它被带到函数之外时,它会生成其他数字

如何在函数中生成不重复的随机数

from random import *
randomEnemyNames = ["Gandalf", "Batman", "Magikarp", "Ed Sheeran", "Justin Bieber"]
class Character(object):
    def __init__(self, name):
        self.name = name
        self.attackPhysical = getrandbits(4)
        self.attackMagical = getrandbits(5)
        self.enemyAttack = getrandbits(6)
        self.critChance = random()
        self.randomHeal = getrandbits(3)
    def attack(self, enemy):
        #inside the class and functions
        print self.critChance #testing with two trials to see if all of it goes random in different ways
        print self.critChance
        print self.attackPhysical
        print self.attackPhysical
        print self.attackMagical
        print self.attackMagical
        print enemy.enemyAttack
        print enemy.enemyAttack
        print self.critChance
        print self.critChance
        print self.randomHeal
        print self.randomHeal
        print self.name
        print enemy.name
the_player = Character("Roy")
the_enemy = Character(choice(randomEnemyNames))
the_player.attack(the_enemy)
#outside the class and functions
print random()
print getrandbits(3)
print getrandbits(4)
print getrandbits(5)
print getrandbits(6)
raw_input("Enter to exit")

您正在为类的这些属性赋值,而不是为代码赋值,它可能看起来像这样:

def getrandbits(n):
    return 9  # I rolled 3d6

class Character:
    def __init__(self):
        self.attackPhysical = getrandbits(4)
    def attack(self, enemy):
        print(self.attackPhysical)
        print(self.attackPhysical)
每次都需要生成一个新的数字。也许像:

class Character:
    def __init__(self):
        self.attackPhysical = 4
    def roll(self, n):
        return getrandbits(n)
    def attack(self, enemy):
        physical_dmg = self.roll(self.attackPhysical)

谢谢你给我答案!我有另一个问题,但我会设法解决它。无论如何,非常感谢你!