What is the scope of a random seed in Python?

前端 未结 1 723
醉话见心
醉话见心 2021-02-05 04:03

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?

1条回答
  •  清酒与你
    2021-02-05 04:15

    Yes, the seed is set for the (hidden) global Random() instance in the module. From the documentation:

    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.

    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.

    0 讨论(0)
提交回复
热议问题