Home > Net >  How to continue calling __init__ funtion until certain condition meet?
How to continue calling __init__ funtion until certain condition meet?

Time:10-25

Take the below code for an example.

import random
class test:
    def __init__(self):
        x = random.choice([1,2,3])
        print(x)
        if x == 2:
            pass

What I want to do here is that when x equals 2 then run the function again and get the different value of x. Therefore whenever I call the test class it always assigns the x value other than 2.

NOTE: We must run the random.choice() in the __init__ and always get the value other than 2, it's okay to run the __init__ as many times as we want unless we get the different value. The value of x is random.

What I have tried

class test:
    def __init__(self):
        x = random.choice([1,2,3])
        if x != 2:
            self.x = x
        else:
            test()

CodePudding user response:

Try This

class test:
    def __init__(self):
        x = random.choice([1,2,3])
        while x == 2:
            x = random.choice([1,2,3])

CodePudding user response:

You really don't want to be calling init recursively. If you're using Python 3.8 there's a neat way to fulfil your requirement.

class test:
  def __init__(self):
    while (x := random.choice([1,2,3])) == 2:
      pass

At some point the while loop will terminate when x is either 1 or 3

  • Related