gpt4 book ai didi

python - 如何在python函数中添加自定义参数参数?

转载 作者:行者123 更新时间:2023-12-01 09:09:34 24 4
gpt4 key购买 nike

我的名字叫 Piyush,我刚刚开始学习用 Python 编写代码。现在我正在做一个项目。如果有人可以帮助在函数中添加自定义参数,我将非常感激。我在下面提到我的代码和我面临的问题:

class Chips ():
def __init__ (self, total):

while True:
try:
total = int(input("How many chips as total?: ?"))

except:
print("Please enter an integer")

else:
break

self.total = total
self.bet = 0

def win_bet (self):
self.total = self.total + self.bet

def loose_bet (self):
self.total = self.total - self.bet

但是,我可以设置总计 = 100 并可以运行游戏,但我希望用户能够输入他/她想要添加的筹码总数。

我希望 while 循环中的输入(总计)作为运行游戏时的参数。但我不断收到此错误:

--
TypeError Traceback (most recent call last)
<ipython-input-9-b1b7b1c195f7> in <module>()
367
368 # Set up the Player's chips
--> 369 player_chips = Chips() # remember the default value is 100
370
371 # Prompt the Player for their bet:

TypeError: __init__() missing 1 required positional argument: 'total'

请帮忙!

感谢您关注我的请求。

最佳答案

您的类在其构造函数中接受一个参数,但您也从构造函数的输入中读取它。

我认为您对在这里想要实现的目标感到困惑。

选项 1:

如果代码的调用者(构造类的代码)可以修改并在实例创建时知道total,则只需在构造函数调用中添加参数即可。

total = 100
player_chips = Chips(total)

选项 2:

如果您无法修改调用者(很可能是我读到的内容),那么这意味着您想实际从输入中读取总数。从构造函数中删除参数。

def __init__ (self):

而不是

def __init__(self, total):

关于python - 如何在python函数中添加自定义参数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com