I’ve run into something I don’t understand. This code:
<code>import random
class MyRandom(random.Random):
pass
r = random.Random()
r.seed(10)
print(r.randint(0, 20))
print(r.randint(0, 20))
print(r.randint(0, 20))
print("------------")
r2 = MyRandom()
r2.seed(10)
print(r2.randint(0, 20))
print(r2.randint(0, 20))
print(r2.randint(0, 20))
</code>
<code>import random
class MyRandom(random.Random):
pass
r = random.Random()
r.seed(10)
print(r.randint(0, 20))
print(r.randint(0, 20))
print(r.randint(0, 20))
print("------------")
r2 = MyRandom()
r2.seed(10)
print(r2.randint(0, 20))
print(r2.randint(0, 20))
print(r2.randint(0, 20))
</code>
import random
class MyRandom(random.Random):
pass
r = random.Random()
r.seed(10)
print(r.randint(0, 20))
print(r.randint(0, 20))
print(r.randint(0, 20))
print("------------")
r2 = MyRandom()
r2.seed(10)
print(r2.randint(0, 20))
print(r2.randint(0, 20))
print(r2.randint(0, 20))
…prints:
<code>18
1
13
------------
18
1
13
</code>
<code>18
1
13
------------
18
1
13
</code>
18
1
13
------------
18
1
13
This is as expected, since it’s the same seed. But if I innocuously override the random() method like this:
<code>import random
class MyRandom(random.Random):
def random(self):
return super().random()
r = random.Random()
r.seed(10)
print(r.randint(0, 20))
print(r.randint(0, 20))
print(r.randint(0, 20))
print("------------")
r2 = MyRandom()
r2.seed(10)
print(r2.randint(0, 20))
print(r2.randint(0, 20))
print(r2.randint(0, 20))
</code>
<code>import random
class MyRandom(random.Random):
def random(self):
return super().random()
r = random.Random()
r.seed(10)
print(r.randint(0, 20))
print(r.randint(0, 20))
print(r.randint(0, 20))
print("------------")
r2 = MyRandom()
r2.seed(10)
print(r2.randint(0, 20))
print(r2.randint(0, 20))
print(r2.randint(0, 20))
</code>
import random
class MyRandom(random.Random):
def random(self):
return super().random()
r = random.Random()
r.seed(10)
print(r.randint(0, 20))
print(r.randint(0, 20))
print(r.randint(0, 20))
print("------------")
r2 = MyRandom()
r2.seed(10)
print(r2.randint(0, 20))
print(r2.randint(0, 20))
print(r2.randint(0, 20))
Suddenly it prints:
<code>18
1
13
------------
20
9
6
</code>
<code>18
1
13
------------
20
9
6
</code>
18
1
13
------------
20
9
6
Why on earth would that change anything? How is the call to super somehow upsetting the internal state?
Even weirder, there isn’t a discrepancy if I’m calling r.random()
instead of r.randint()
. Perhaps that clue will be helpful.
3