1

Stack Overflow 上也有类似的问题,但我在代码中找不到我做错了什么。

def copyPic():
  file=pickAFile()
  oldPic=makePicture(file)
  newPic=makeEmptyPicture(getWidth(oldPic),getHeight(oldPic))
  for y in range(0,getHeight(oldPic)):
    for x in range(0,getWidth(oldPic)):
      oldPixel=getPixel(oldPic,x,y)
      colour=getColor(oldPixel)
      newPixel=getPixel(newPic,x,y)
      setColor(newPixel,colour)
explore(newPic)

当我使用explore(newPic)show(newPic)在函数之外时,给出一个空白的白色画布。

这是因为 newPic 没有保存吗?如何“保存”对 newPic 的更改?

4

1 回答 1

4

这是scope变量的问题:

当您定义一个函数(此处copyPic())时,该函数内创建的所有变量仅对该函数“可见”。全球计划对其存在一无所知。

Python 解释器按照编写的顺序(按顺序)读取代码。正如newPic首先在函数中定义的那样,它属于它,并且一旦函数终止就会被销毁。这就是为什么你不能参考newPic以后。要解决此问题,您必须返回变量(关键字),以便在调用函数return时可以从主程序中获取它。copyPic()

您必须执行以下操作:

def copyPic():
  file=pickAFile()
  oldPic=makePicture(file)
  newPic=makeEmptyPicture(getWidth(oldPic),getHeight(oldPic))
  for y in range(0,getHeight(oldPic)):
    for x in range(0,getWidth(oldPic)):
      oldPixel=getPixel(oldPic,x,y)
      colour=getColor(oldPixel)
      newPixel=getPixel(newPic,y,x)
      setColor(newPixel,colour)

  return newPic      # HERE IS THE IMPORTANT THING

newPic = copyPic()   # Here we assign the returned value to a new variable
                     # which belong to the "global scope".
explore(newPic)

注意:在这里,我使用了 2 个变量,它们的名称相同newPic。Jython 解释器将它们视为两个不同的变量:

  • 第一个属于函数(function scope)
  • 第二个属于主程序(也叫global作用域)

因此,上面的代码完全等同于这个:

def copyPic():
  file=pickAFile()
  ...
  return newPic    

newPic_2 = copyPic()    # Here we store / assign the "newPic" returned by the 
                        # copy function into another variable "newPic_2" (which
                        # is a "global variable").
explore(newPic_2)



编辑 :

所有这一切的替代方法是使用global关键字告诉解释器newPic要从全局范围中找到:

newPic = None           # First declare "newPic" globally.

def copyPic():
  global newPic         # Tell the function to refer to the global variable.
  ...
  #return newPic        # No need to return anything, the function is 
                        # modifying the right variable.

copyPic()
explore(newPic)

请注意,一般来说,尽量避免使用全局变量。总是有更好的设计,特别是显然是面向对象的 Python ......


我希望我说清楚了。如果没有,请不要犹豫,要求进一步的解释。

于 2013-06-23T00:20:58.147 回答