【问题标题】:Passing lists to methods in classes将列表传递给类中的方法
【发布时间】:2017-08-06 14:34:12
【问题描述】:

我有以下问题,在详细解释之前,我想先展示以下两个最小类来说明:

class Example1:

    def __init__(self):
        pass

    def function11(self,x):
        x=2*x+1
        return x

    def function12(self,x):
        y=0
        z=x
        while y<z:
            x=self.function11(x)
            y=y+1
        return x

class Example2:# the only difference to the previous class: it handles 
               #lists instead of numbers

    def __init__(self):
        pass

    def function21(self,x):
        x[0]=2*x[0]+1
    return x

    def function22(self,x):
        y=0
        z=x[0]
        while y<z:
            x=self.function21(x)
            y=y+1
        return x    



if __name__=="__main__":
    A1=Example1()
    x1=A1.function11(3)
    y1=A1.function12(x1)
    print'Result of Example1:'
    print x1
    print y1
    print 

    A2=Example2()
    x2=A2.function21([3])
    y2=A2.function22(x2)
    print'Result of Example2:'
    print x2
    print y2

这是输出:

Result of Example1:
7
1023

Result of Example2:
[1023]
[1023]
>>>

我在这里不明白的是:为什么变量 x2 会被 y2 的值​​覆盖?这显然取决于列表是 Python 中的可变对象这一事实,对吗?我对此的搜索使我找到了Effbot 的一篇文章。不过,我真的不明白这里发生了什么。

【问题讨论】:

  • 因为,在Example2.function21 中,您正在传递一个列表对象并通过其索引对其进行变异(在x[0]=2*x[0]+1 中)。在Example1.function11 中,您并没有改变原始变量(只是通过x=2*x+1 将名称重新分配给不同的对象)
  • 阅读 this answer 可能会有所帮助

标签: python list class


【解决方案1】:

function12function12 不会改变它们的输入参数(顺便说一句,对于不可变类型,例如int,这是不可能的)。他们只是根据参数计算一个结果,将名称 x 重新绑定到该计算的值,然后返回该结果。

function21function22 改变他们的输入参数然后返回它。

这就是它的全部内容。下面是对输入参数有和没有副作用的函数的简短演示:

>>> def no_sideeffects(x):
...     return x + [1] # build a new list and return the result, don't touch x
... 
>>> x = [0]
>>> no_sideeffects(x)
[0, 1]
>>> x
[0]
>>> 
>>> def sideeffects(x):
...     x[0] = 23 # mutate x, i.e. change value at index 0
...     return x # then return it
... 
>>> x
[0]
>>> sideeffects(x)
[23]
>>> x
[23]

【讨论】:

    【解决方案2】:

    Example1Example2 之间的区别在于,您在Example1 中返回一个值,而在Example2 中返回一个列表
    Example2 返回传递给它的同一个列表,因此,当您调用 function22 时,您重新使用同一个列表,因此它的值被覆盖。

    【讨论】:

      猜你喜欢
      • 2011-01-01
      • 2020-11-14
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      相关资源
      最近更新 更多