小编Ahm*_*fi'的帖子

为什么 Python 中的临时变量会改变此共享传递变量的行为方式?

第一次在这里提问,所以请强调我的错误。

我正在研究一些 Leetcode,并在 Python 中遇到了一种行为(与问题无关),我无法完全弄清楚也无法通过谷歌搜索。这特别困难,因为我不确定我是否缺乏理解:

  1. 递归
  2. Python 中的运算符+=或一般变量赋值
  3. 或者Python的传递共享行为
  4. 或者完全是别的东西

这是简化的代码:

class Holder:
    def __init__(self, val=0):
         self.val = val

class Solution:
    def runThis(self):
        holder = Holder()
        self.diveDeeper(holder, 5)
        return 
        
    def diveDeeper(self, holder, n):
        if n==0:
            return 1

        # 1) Doesn't result in mutation
        holder.val += self.diveDeeper(holder, n-1)

        # 2) Also doesn't result in mutation
        # holder.val = holder.val + self.diveDeeper(holder, n-1)

        # 3) !! Results in mutations
        # returnVal = self.diveDeeper(holder, n-1)
        # holder.val += returnVal

        print(holder.val)
        return …
Run Code Online (Sandbox Code Playgroud)

python recursion pass-by-reference

8
推荐指数
2
解决办法
229
查看次数

标签 统计

pass-by-reference ×1

python ×1

recursion ×1