将列表传递给类中的方法

时间:2017-03-15 17:31:27

标签: python list class

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

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的一篇文章。不过,我真的不明白这里发生了什么。

2 个答案:

答案 0 :(得分:1)

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

function21function22 mutate 输入参数,然后将其返回。

真的就是这一切。这是对输入参数有或没有副作用的函数的简短演示:

>>> 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]

答案 1 :(得分:0)

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

相关问题