如何继续调用 __init__ 函数直到满足某些条件?

How to continue calling __init__ funtion until certain condition meet?

以下面的代码为例

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

这里我想做的是,当x等于2时,再运行这个函数,得到不同的x值。因此,每当我调用 test class 时,它总是分配 2 以外的 x 值。

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.

我试过的

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

更新: 实施 while 循环听起来是个好主意。 试试这个:

import random
class test:
    def __init__(self):
        x = random.choice([1,2,3])
        loop = 0
        while x == 2:
            x = random.choice([1,2,3])
            loop += 1
            if loop >= 5:
                x = False

不可能 return 来自 __init__() 函数的任何值,因为该函数应该 return None,因此我将 x 值设置为假的,如果是你喜欢的,

您真的不想递归调用 init。如果您使用的是 Python 3.8+,那么有一种巧妙的方法可以满足您的要求。

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

在某些时候,当 x 为 1 或 3 时,while 循环将终止