当我将变量传递给另一个方法时,如何求解method()需要1个位置参数,但给出了2个位置参数

问题描述 投票:0回答:2

我想传递在Hangman_figure的main_game中声明的机会变量

def hangman_figure(chance):
    print("hello world")

    if chance==8:

        print("Select another letter")
        print(chance)

    elif chance== 7:
        print("O")
    elif chance==6:
        print("O")
        print('|')

这是声明我的变量的方法

def main_game(self):

    spaces=[]
    chance=9
    for space in range(0,self.word_len):
        spaces.append('_ ')
        print(spaces[space],end=" ")


    for x in range(1,10):
        choose =input('Kindly choose a letter that you think this word contains :')
        if choose in self.word_store:
            position=self.word_store.index(choose)
            spaces[position]= choose
            for y in range(0,self.word_len):
                print(spaces[y],end=" ")


            print("Great!! This letter is present in the word, Keep Going")

        else:
            chance=chance-1 
            #I have declared this chance variable which I need to use

            print("Sorry this letter does not exist in the word")

            self.hangman_figure(chance)   

如何在我的hangman_figure方法中传递这个机会变量

python python-3.x methods parameter-passing
2个回答
1
投票

我想您正在使用课程。给定您的方法hangman_figure,需要将self作为参数。更正的方法:

def hangman_figure(self, chance):
   print("hello world")

否则,self.hangman_figure(chance)中的main.py将导致错误,因为您在类实例上调用了该方法,该实例被视为提供了一个参数,并且您还提供了chance作为一个参数。


1
投票

很难从您的代码格式和有限的片段中分辨出来,但是从您对self.hangman_figure的使用看来,hangman_figure似乎是一个类方法,因此您需要为self添加一个参数:

def hangman_figure(self, chance):

[您收到此错误,是因为Python隐式地将类的实例传递给self参数,因此仅定义def hangman_figure(chance)时,它将解释chance参数以充当[ C0]参数(因为self参数实际上没有have命名为self),因此当您使用self传递另一个参数时,由于您传递了两个参数((包括隐式self.hangman_figure(chance))而不是原始函数定义中包含的一个参数

© www.soinside.com 2019 - 2024. All rights reserved.