Python中随机种子的范围是什么? [英] What is the scope of a random seed in Python?
问题描述
如果我在模块的一个类中使用Python函数random.seed(my_seed)
,该种子是否会在该模块中实例化的所有其他类中保留?
If I use the Python function random.seed(my_seed)
in one class in my module, will this seed remain for all the other classes instantiated in this module?
推荐答案
是的,为模块中的(隐藏)全局Random()
实例设置了种子.从文档:
Yes, the seed is set for the (hidden) global Random()
instance in the module. From the documentation:
此模块提供的功能实际上是
random.Random
类的隐藏实例的绑定方法.您可以实例化自己的Random
实例,以获取不共享状态的生成器.
The functions supplied by this module are actually bound methods of a hidden instance of the
random.Random
class. You can instantiate your own instances ofRandom
to get generators that don’t share state.
如果需要将种子分开,请使用单独的Random()
实例;您可以在实例化时传递新的种子:
Use separate Random()
instances if you need to keep the seeds separate; you can pass in a new seed when you instantiate it:
>>> from random import Random
>>> myRandom = Random(anewseed)
>>> randomvalue = myRandom.randint(0, 10)
该类支持与模块相同的接口.
The class supports the same interface as the module.
这篇关于Python中随机种子的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!