[Python] Subclassing random.Random produces different results with same seed

Discussão em 'Python' iniciado por Stack, Setembro 10, 2024.

  1. Stack

    Stack Membro Participativo

    I've run into something I don't understand. This 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:

    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:

    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:

    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.

    Continue reading...

Compartilhe esta Página