Home > OS >  How to re-run random. in the instantiation of a child class in python?
How to re-run random. in the instantiation of a child class in python?

Time:04-09

So I'm trying to create a method in a parent class that requires an attribute that is a random integer in between (number a) and (number b), the value being instantiated before hand. But for each child class I want to instantiate a different random integer in between different numbers, say (number c) and (number d). It kind of works generating numbers for each class differently but each time the method runs for the classes, the instantiated number is the saved as the same number for each class without every re-randomizing. I want it to randomize each time the method is called.

import random

class Parent:
  def __init__(self):
    self.random = random.randint(1, 10)

  def randomize(self):
     print(self.random)

class Child(Parent):
  def __init__(self):
    self.random = random.randint(11, 20)

a = Parent()
b = Child()

a.randomize()
a.randomize()
a.randomize()

b.randomize()
b.randomize()
b.randomize()

First Output:

9
9
9
15
15
15

Second Output:

3
3
3
19
19
19

I want each time the method is called to randomize a different number while having different ranges for the number to be randomized from for each class. The goal is to not have to copy/past the method to each class a different .randint hardcoded in.

CodePudding user response:

See @johnsharpe's comment. You should put the lower and upper bounds as parameters and then call random.randint each time you want to randomize.

import random

class Parent:
  def __init__(self, a=1, b=10):
    self.a = a
    self.b = b
    self.random = random.randint(self.a, self.b)

  def randomize(self):
    self.random = random.randint(self.a, self.b)
    print(self.random)

class Child(Parent):
  def __init__(self):
    super().__init__(11, 20)
  • Related