<p>在<code>flip()</code>函数中(就像在任何函数中一样),如其他答案所述,返回<code>picture</code>,这是作为函数参数传递的图像,但在d()中定义。。。</p>
<p>这是一个变量的<code>scope</code>问题,所以我请您再看一下我们讨论的<a href="https://stackoverflow.com/a/17256599/1715716">here</a>。</p>
<p>在这里,你有两个选择(你在两者之间做了一个融合):</p>
<ul>
<li>直接修改作为参数给定的<code>picture</code></li>
<li>创建一个<code>newPicture</code>,修改它,最后返回它</li>
</ul>
<p><strong>有关二维选项的详细信息:</strong></p>
<p>这里重要的是<code>picture</code>变量属于<code>d()</code>函数(d()是它的作用域)。同时,<code>newPicture</code>变量属于<code>flip()</code>函数(flip()是其作用域)。因此,newPicture的生命周期是flip()(即,在返回时,只要终止flip()函数的执行,它就会被销毁)。而d()对这个新图片一无所知,除非你把它还给d()。</p>
<p>简而言之(假设我们在讨论第二种选择):</p>
<p><strong>1)</strong>创建一个以<code>picture</code>作为参数的函数(flip())</p>
<p><strong>2)</strong>在flip()中,创建一个局部变量<code>newPicture</code>,并只修改该变量,使原始的<code>picture</code>保持不变</p>
<p><strong>3)</strong>将新更新的<code>newPicture</code>返回给父<code>scope</code>。这里d()调用flip(),所以它是父作用域。我们必须创建一个3d变量(属于d()作用域),以掌握flip()返回的内容:</p>
<pre><code>def flip(picture)
# Create newPicture
# Modify newPicture (using the information from the "picture" parameter)
setColor(newPicture, ...)
...
return newPicture
def d():
file = PickAFile()
original_pic = makePicture(file)
finalNewPicture = flip(original_pic) # {1}
show(finalNewPicture)
</code></pre>
<p>{1}:这里我们将flip返回的值(即<code>newPicture</code>)赋给更高作用域<code>finalNewPicture</code>的变量(处理程序)。。。</p>
<p>我希望它能帮助你理解这背后的逻辑。就像俄罗斯玩偶:newPicture在flip()中使用,在d()中使用。。。</p>
<hr/>
<p><strong>编辑:</strong></p>
<p>我还想解释一下第一种选择。。。</p>
<p><strong>1)</strong>创建一个以<code>picture</code>作为参数的函数(flip())</p>
<p><strong>2)</strong>在flip()中,直接修改更大范围的<code>picture</code>变量</p>
<p><strong>3)</strong>不要返回flip()中的任何内容</p>
<p>这将导致:</p>
<pre><code>def flip(picture)
# Simply modify the variable "picture", given as a parameter
setColor(picture, ...)
...
# Do not return anything
def d():
file = PickAFile()
original_pic = makePicture(file)
flip(original_pic) # {1}
show(original_pic)
</code></pre>
<p>{1}:这里flip()直接对输入图片进行了更改,因此我们可以直接显示原始的修改图片(<code>original_pic</code>)。不需要中间处理程序变量。</p>
<hr/>
<p><strong><em>选项1的代码:</em></strong>(因为您已经将其用于选项2)</p>
<pre><code>def flip(picture):
height = getHeight(picture)
width = getWidth(picture)
x2=width-1
for x in range(0, width/2): # Only process the half way
y2=0
for y in range(0, height):
# swap pix and pix2
pxl = getPixel(picture, x, y)
pxl2 = getPixel(picture, x2, y2)
color = getColor(pxl)
color2 = getColor(pxl2)
setColor(pxl2, color)
setColor(pxl, color2)
y2=y2+1
x2=x2-1
def d():
f = pickAFile()
original_picture = makePicture(f)
flip2(original_picture)
show(original_picture)
d()
</code></pre>
<p><strong><em>注意:</em></strong>翻转可以被广泛简化如下:</p>
<pre><code>def flip2(picture):
height = getHeight(picture)
width = getWidth(picture)
for x in range(0, width/2): # Only process the half way
for y in range(0, height):
# swap pix and pix2
pxl = getPixel(picture, x, y)
pxl2 = getPixel(picture, width-1-x, y)
color = getColor(pxl)
color2 = getColor(pxl2)
setColor(pxl2, color)
setColor(pxl, color2)
</code></pre>