我需要帮助解决这个问题:我创建了一个类,它的引用是一个随机数。问题是这样的:每次调用那个类时,我都会得到相同的数字,这使得随机的使用变得毫无意义;有什么办法可以解决吗?
import random
class dicethrow:
result = random.randint (1,6)
a = dicethrow ()
b = dicethrow ()
使用这个,a == b 总是,我需要它们是不同的。 谢谢!
最佳答案
在您的情况下,result
是一个类(或静态)变量 - 它被定义一次并且对所有实例都相同。
在__init__()
方法中定义result
:
import random
class dicethrow:
def __init__(self):
self.result = random.randint(1,6)
a = dicethrow()
b = dicethrow()
print a.result
print b.result
另见:
关于python - 每次调用类时都需要创建随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102531/