Python - class 对象 return 值
Python - class object return value
这里是初学者 Pythonista
制作博彩游戏作为 OOP 练习的一部分。
创建了一个具有下注功能的玩家class:
# Player Class
class Player():
def __init__(self,name):
self.name = name
self.hand = []
self.chips = 0
def deposit(self,amount):
self.chips += int(amount)
print(f"{amount} chips deposited.\nTotal available funds: {self.chips}")
def bet(self):
amount = int(input("Place your bet: "))
if not amount > self.chips:
self.chips -= amount
print(f"You bet {amount}. New Balance: {self.chips}")
return amount
else:
print("You cannot bet above your chips")
我的印象是 class 中的方法充当函数,但是“return 数量”命令 return 是“None/NoneType”。
如何 return 将要添加的整数值分配给变量?
提前致谢
可能通过了 else 语句,但没有 return 任何东西。尝试了您的代码,如果您满足下注函数中的条件(具有 return)
的条件,它会按预期工作
a.chips = 100
a.bet()
Place your bet: >? 1
You bet 1. New Balance: 99
Out[8]: 1
除了 else 条件外,您的代码似乎是正确的。您应该在方法 bet
中添加 else 条件
return 0
或报错
raise ValueError('You cannot bet above your chips')
那么你应该在任何你想使用它的地方处理它。
我遇到了缩进错误。 bet 方法中的 If 语句不应缩进。修复后它对我来说很好用。
正在从 class 玩家创建对象:
test_player = Player("TestName")
提供一些押金:
test_player.deposit(10)
10 chips deposited.
Total available funds: 10
最后是投注:
test_player.bet()
Place your bet: >? 5
You bet 5. New Balance: 5
最后一次投注给出:
test_player.bet()
Place your bet: >? 6
You cannot bet above your chips
这里是初学者 Pythonista
制作博彩游戏作为 OOP 练习的一部分。
创建了一个具有下注功能的玩家class:
# Player Class
class Player():
def __init__(self,name):
self.name = name
self.hand = []
self.chips = 0
def deposit(self,amount):
self.chips += int(amount)
print(f"{amount} chips deposited.\nTotal available funds: {self.chips}")
def bet(self):
amount = int(input("Place your bet: "))
if not amount > self.chips:
self.chips -= amount
print(f"You bet {amount}. New Balance: {self.chips}")
return amount
else:
print("You cannot bet above your chips")
我的印象是 class 中的方法充当函数,但是“return 数量”命令 return 是“None/NoneType”。
如何 return 将要添加的整数值分配给变量?
提前致谢
可能通过了 else 语句,但没有 return 任何东西。尝试了您的代码,如果您满足下注函数中的条件(具有 return)
的条件,它会按预期工作a.chips = 100
a.bet()
Place your bet: >? 1
You bet 1. New Balance: 99
Out[8]: 1
除了 else 条件外,您的代码似乎是正确的。您应该在方法 bet
中添加 else 条件return 0
或报错
raise ValueError('You cannot bet above your chips')
那么你应该在任何你想使用它的地方处理它。
我遇到了缩进错误。 bet 方法中的 If 语句不应缩进。修复后它对我来说很好用。
正在从 class 玩家创建对象:
test_player = Player("TestName")
提供一些押金:
test_player.deposit(10)
10 chips deposited.
Total available funds: 10
最后是投注:
test_player.bet()
Place your bet: >? 5
You bet 5. New Balance: 5
最后一次投注给出:
test_player.bet()
Place your bet: >? 6
You cannot bet above your chips