【问题标题】:Python - class object return valuePython - 类对象返回值
【发布时间】:2021-04-19 11:34:44
【问题描述】:

这里是 Python 初学者

将投注游戏作为 OOP 练习的一部分。

制作了一个带有下注功能的 Player 类:

# 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")

我的印象是类中的方法充当函数,但是“return amount”命令返回“None/NoneType”。

如何返回要添加的整数值以分配给变量?

提前致谢

【问题讨论】:

    标签: python oop methods return-type


    【解决方案1】:

    可能通过了 else 语句,它不返回任何东西。尝试了您的代码,如果您满足下注功能中的条件(有回报的条件),它会按预期工作

    a.chips = 100
    a.bet()
    Place your bet: >? 1
    You bet 1. New Balance: 99
    Out[8]: 1
    

    【讨论】:

      【解决方案2】:

      除了 else 条件之外,您的代码似乎是正确的。您应该在方法 bet 中添加 else 条件

      return 0
      

      或引发错误

      raise ValueError('You cannot bet above your chips')
      

      那么你应该在任何你想使用它的地方处理它。

      【讨论】:

        【解决方案3】:

        对我来说有一个缩进错误。 bet 方法中的 If 语句不应缩进。修复后它对我来说很好。

        从 Player 类创建一个对象:

        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
        

        【讨论】:

        • 很抱歉出现缩进错误。在这里写代码是个错误。它不在原始代码中
        猜你喜欢
        • 2013-02-01
        • 2017-06-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-26
        • 2013-08-03
        • 2016-04-18
        • 2012-09-06
        • 1970-01-01
        相关资源
        最近更新 更多