以下面的代碼為例。
import random
class test:
def __init__(self):
x = random.choice([1,2,3])
print(x)
if x == 2:
pass
我想在這里做的是,當 x 等于 2 時,再次運行該函式并獲得不同的 x 值。因此,每當我呼叫test該類時,它總是分配 2 以外的 x 值。
注意:我們必須運行
random.choice()in__init__并始終獲得2以外的值,__init__除非我們獲得不同的值,否則可以根據需要多次運行。的值x是隨機的。
我試過的
class test:
def __init__(self):
x = random.choice([1,2,3])
if x != 2:
self.x = x
else:
test()
uj5u.com熱心網友回復:
你真的不想遞回呼叫init。如果您使用的是 Python 3.8 ,那么有一種巧妙的方法可以滿足您的要求。
class test:
def __init__(self):
while (x := random.choice([1,2,3])) == 2:
pass
在某些時候,當 x 為 1 或 3 時,while回圈將終止
uj5u.com熱心網友回復:
更新: 實作 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
不可能從__init__()函式回傳任何值,因為該函式應該回傳 None,因此我已將 x 值設定為 False,如果它是您想要的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336419.html
