python3:从类中调用函数来模拟switch语句不起作用

2024-10-03 06:25:50 发布

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

我正在写一个程序,这是一个模拟游戏的一个变种石头,布剪刀游戏。在我的main函数中,我输出一个接口,然后尝试调用其中定义的方法,该方法充当switch语句。我得到了:“makeSel()缺少1个必需的位置参数:'self'”类型错误。我在网络上搜索过任何提示,但是没有找到任何有用的提示。我试图将“makeSel()”更改为Main.makeSel公司()“但它给了我一个主要是未定义的。在


class Main:

    def makeSel(self):
        selection = input()
        if(selection == 1):
            return StupidBot('StupidBot')
        elif(selection == 2):
            return RandomBot('RandomBot')
        elif(selection == 3):
            return IterativeBot('IterativeBot')
        elif(selection == 4):
            return LastPlayBot('LastPlayBot')
        elif(selection == 5):
            return MyBot('MyBot')
        elif(selection == 6):
            return HumanPlayer('HumanPlayer')
        else:
            print('Invalid selection, please try again.  Enter 1, 2, 3, 4, 5, or 6')
            makeSel()

    print('')
    print('Welcome to my Rock-Paper-Scissors-Lizard-Spock game!')
    print('')
    print('Please select two players, enter 1, 2, 3, 4, 5, or 6')
    print('  (1) -> StupidBot')
    print('  (2) -> RandomBot')
    print('  (3) -> IterativeBot')
    print('  (4) -> LastPlayBot')
    print('  (5) -> MyBot')
    print('  (6) -> HumanPlayer')

    p1 = makeSel()
    p2 = makeSel()

我希望有人能对我所经历的问题有所了解。在


Tags: or方法selfreturnmainprintelifmybot
1条回答
网友
1楼 · 发布于 2024-10-03 06:25:50

要修复立即数but,请将makeSel()更改为self.makeSel()self不像其他一些语言那样,在Python中不会隐式传递给方法调用。我想你也是指return self.makeSel()。在

另外,我认为您希望在mainSel()中使用一个循环。您正在递归地调用mainSel(),它的工作方式非常类似于循环,但会填充调用堆栈。在

class Main:

    def makeSel(self):
        while True
            selection = input()
            if(slection == 1):
                return StupidBot('StupidBot')
            elif(slection == 2):
                return RandomBot('RandomBot')
            elif(selection == 3):
                return IterativeBot('IterativeBot')
            elif(selection == 4):
                return LastPlayBot('LastPlayBot')
            elif(selection == 5):
                return MyBot('MyBot')
            elif(selection == 6):
                return HumanPlayer('HumanPlayer')
            else:
                print('Invalid selection, please try again.  Enter 1, 2, 3, 4, 5, or 6')

相关问题 更多 >