【问题标题】:Is there a way to take a value from a function without returning it? [closed]有没有办法从函数中获取值而不返回它? [关闭]
【发布时间】:2022-01-19 12:04:46
【问题描述】:

我正在为壁球比赛计分系统编写代码,并且已经返回 2 个值。如果我返回另一个值,它会弄乱我代码中的其他函数。所以我想知道是否有任何方法可以在函数之外访问 pointCount 值而不返回它?

【问题讨论】:

  • 将代码放在一个类中并使用属性
  • 可以显示需要访问pointCount的代码吗?
  • 创建类函数或使用全局变量
  • 请避免使用全局变量 :D 这是问题的根源!
  • “如果我返回另一个值,它会弄乱我代码中的其他函数”——更改其他函数以免弄乱它们?

标签: python return


【解决方案1】:

一个可能的解决方案是在函数外部有一个全局变量,例如在函数内部更改它

pointCount = 0

def engGame(ra,rb):
    global pointCount # define pointCount as a global variable
    # the rest of the function

engGame(a, b)
# pointCount will be changed here

【讨论】:

    【解决方案2】:

    我不建议这样做,但一种快速的方法是使用全局变量,你必须先声明它

    pointCount = 0
    
    def eng_Game(ra,rb):
        global pointCount
        win = False
        winCondition = 9
        aServer = False
        bServer = False
        aScore = 0
        bScore = 0
        serverNum = random.randint(1,2)
        if serverNum == 1:
            aServer = True
        else: bServer = True
        while win == False:
            pointCount += 1
            ProbAWin = ra/(ra+rb)
            ProbBWin = rb/(rb+ra)
            ranNum = random.random()
            if ranNum < ProbAWin and aServer:
                aScore += 1
            elif ranNum < ProbAWin and aServer == False:
                aServer = True
                bServer = False
            elif ranNum > ProbAWin and bServer:
                bScore += 1
            elif ranNum > ProbAWin and bServer == False:
                bServer = True
                aServer = False
            if aScore == winCondition or bScore == winCondition:
                return aScore,bScore
            elif aScore == 8 and bScore == 8:
                playTo = random.randint(1,2)
                if playTo == 1:
                    winCondition = 10
    
    
    

    您现在可以在函数外部使用pointCount 变量访问它。

    这样做的正确方法是声明一个类并在类中初始化变量,然后使用 self.variable 名称来访问和修改它们。这是一个很好的起点,https://www.w3schools.com/python/python_classes.asp 语法很容易理解。

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多