1

スタック オーバーフローにも同様の質問がありますが、自分のコードで間違っていることを見つけることができません。

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 Interpreter によって 2 つの異なる変数と見なされます。

  • 最初のものは関数に属します (関数スコープ)
  • 2番目のものはメインプログラムに属します(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 に答える