How to use Python's random number generator with a local seed?

守給你的承諾、 提交于 2020-01-23 05:12:56

问题


Python's random seems are global, so modules changing it will effect each other.

While there are of course many 3rd party modules, is there a way using Python's standard library to have a random number local to a context.

(without using random.get/setstate which may be problematic when mixing code from different modules).

Something like...

r = random.context(seed=42)
number = r.randint(10, 20)

Where each module can use its own random context.


回答1:


From the docs:

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 of Random to get generators that don’t share state.

Make your own random.Random instance and use that.

rng = random.Random(42)
number = rng.randint(10, 20)


来源:https://stackoverflow.com/questions/37355985/how-to-use-pythons-random-number-generator-with-a-local-seed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!