如何通过相同的函数重新启动函数?

2024-09-29 23:15:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过函数本身重新启动函数?下面是函数的内容:

class thingamajig():
    def __init__(self):
        pass
    def dostuff(self):
        number = random.randint(0, 3)
        if number == 3:
            #restart here??????
thing = thingamajig()
thing.dostuff()

如何重新启动该功能


Tags: 函数selfnumber内容ifinitdefrandom
3条回答

在dostuff中创建while循环,例如:

def dostuff(self):
    whatever you need the code to do
    doagain = input('Want to do this again? y/n ')
    while doagain != 'n':
        whatever you need the code to do
        doagain = input('Want to do this again? y/n ')

注意,必须使用C++中的D/while循环来解决必须重新编码代码的问题,但对于Python

则如此。

这就是你如何做到的:

class thingamajig():
    def __init__(self):
        pass
    def dostuff(self):
        number = random.randint(0, 3)
        if number == 3:
            self.dostuff()
thing = thingamajig()
thing.dostuff()

这个类只知道它的参数和它自己的变量。Self是一个会说“this class”的关键字

那么:

class thingamajig():
    def __init__(self):
      pass
    def dostuff(self):
        doagain = input('Want to do this again? y/n ')
        if doagain == 'y':
            self.dostuff()
thing = thingamajig()
thing.dostuff()

相关问题 更多 >

    热门问题