我有以下问题,我想在详细解释之前先显示以下两个最小类来说明:
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 .尽管如此,我还是不太明白这里发生了什么。
请您参考如下方法:
function12 和 function12 不会改变它们的输入参数(顺便说一句,对于诸如 int 之类的不可变类型来说无论如何是不可能的) .他们只是根据参数计算结果,将名称 x 重新绑定(bind)到该计算的值,然后返回该结果。
function21 和 function22 改变它们的输入参数,然后返回它。
这就是它的全部内容。下面是对其输入参数有和没有副作用的函数的简短演示:
>>> 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]
