方法的Python CLI参数



我在为方法创建argparse时遇到问题:我的主要.py

parser = argparse.ArgumentParser()
parser.add_argument( "--word", "-w", help="Find score for word", type=str)
args = parser.parse_args()
second = SecondOption()
print(args.word)
second.score_from_word(args.word)

class SecondOption:

class SecondOption():
def score_from_word(word):
SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
for letter in letters.split()}
score = 0
for w in range(word):
if w in LETTER_SCORES.keys():
score += LETTER_SCORES.get(w)
print(score)

在console:python main.py-w KOT中编写后,我想得到分数(本例为7(,但我得到了TypeError:需要1个参数,但给出了2个。我该怎么解决?

问题是您的SecondOption类中有一个名为score_from_words的绑定方法,其签名不正确。。。或者至少不是你所期望的那样。

由于该方法已绑定到类。发送的第一个arg将是self的实例,始终用于绑定方法(类中的方法(。因此,实际上,这个调用是在查找签名self_from_word(self, word),因此当您只指定一个时,会发送两个参数。

修复方法是将self作为第一个参数添加到绑定方法中。

class SecondOption():
def score_from_word(self, word):
pass

在类内使用函数/方法时,第一个参数应该始终是self。因此,您需要从def score_from_word(word):更改为def score_from_word(self, word):。此外,我在您的代码中发现了另一个错误:for w in range(word):应该是for w in word:,因为您不是想得到字母的位置,而是想得到字母本身。

最新更新