There are similar questions on Stack Overflow, but I cannot find what I am doing wrong in my code.
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)
When I use explore(newPic)
or show(newPic)
outside of the function, gives a blank white canvas.
Is this because the newPic is not saved? How do I 'save' the changes to newPic?
It is a matter of
scope
of the variable :When you define a function (here
copyPic()
) all the variables created inside this function are "visible" by the function only. The global program does not know anything about its existence.The Python interpreter reads the code in the order it is written (sequentially). As
newPic
is defined in the function in the first place, it belong to it and is destroyed once the function terminates. That is why you can't refer tonewPic
afterward. To fix this you have to return the variable (keywordreturn
) such that you can get it from the main program when calling thecopyPic()
function.You have to do as follows :
Note : Here, I used 2 variables called identically
newPic
. Those are considered as two different variables by the Jython Interpreter :global
scope)Thus the code above is exactly equivalent to this one :
EDIT :
An alternative to all of this would have been to use the
global
keyword to tell the interpreter thatnewPic
was to be found from the global scope :Note that generally speaking, one try to avoid using global variables. There is always better designs, specially with Python which is clearly object oriented...
I hope I made myself clear. If not, do not hesitate to ask further explanations.