python random 源代码
时间: 2023-10-07 22:14:48 浏览: 180
randomnum_random_源码
以下是 Python 中 random 模块的源代码:
```
import _random
import math
import os
import sys
import time
class Random(_random.Random):
VERSION = 3 # 版本号
def seed(self, a=None, version=2):
if version == 1 or version == 2 and isinstance(a, (str, bytes, bytearray)):
a = hash(a) # 将字符串类型的种子转换成整数类型的种子
super().seed(a)
elif version == 2 and isinstance(a, int):
super().seed(a)
elif version == 3 and isinstance(a, (str, bytes, bytearray)):
if isinstance(a, str):
a = a.encode()
a += os.urandom(2500)
super().seed(int.from_bytes(hashlib.sha512(a).digest(), 'big'))
else:
raise TypeError("a must be None, int, str or bytes")
def getstate(self):
return self.VERSION, super().getstate()
def setstate(self, state):
version = state[0]
if version == 3:
state = state[1]
super().setstate(state)
def jumpahead(self, n):
if n >= 0:
if n < 2**64:
super().jumpahead(n)
else:
if not isinstance(n, int):
raise TypeError("n must be an integer")
if n < 0:
raise ValueError("n must be non-negative")
while n > 0:
if n & 1:
super().next()
n >>= 1
else:
raise ValueError("n must be non-negative")
def __getstate__(self):
return self.getstate()
def __setstate__(self, state):
self.setstate(state)
_inst = Random()
seed = _inst.seed
random = _inst.random
uniform = _inst.uniform
randrange = _inst.randrange
choice = _inst.choice
shuffle = _inst.shuffle
sample = _inst.sample
choices = _inst.choices
```
这是 random 模块的基础实现,用于生成伪随机数。你可以使用 `import random` 来使用该模块的功能。
阅读全文