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



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

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('|')

这是声明我的变量的方法

定义main_game(个体经营(:

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方法中传递此机会变量

我猜你正在使用一个类。鉴于您的方法hangman_figure需要将self作为参数。更正方法:

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

否则,main.py中的self.hangman_figure(chance)将导致错误,因为您在类实例上调用该方法,该方法计为给出参数,并且还将chance作为参数。

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

def hangman_figure(self, chance):

您收到此错误是因为 Python 隐式传递了类本身的实例来代替self参数,因此使用您对def hangman_figure(chance)的定义,它将chance参数解释为self参数(因为self参数实际上不必命名为self(, 因此,当您使用self.hangman_figure(chance)传入另一个参数时,它会引发错误,因为您传递的是两个参数(包括隐式self(,而不是您包含在原始函数定义中的一个参数

最新更新