Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating and using a driver function. How does it work?

Tags:

python

I am new to python and have been shown 'drivers' for running functions without entering them into the command line,

I don`t understand the concept of drivers or how to type them out correctly, any kind of feedback on how to use them would be great!.

What I don't understand is how entering the function makeGreyscaleThenNegate(pic) can call the def function makeGreyscaleThenNegate(picture): when the input values are different (pic) versus (picture). (I guess this is because I don't know how the 'driver' function works.)

Here is what i've been shown

def driverGrey():
  pic=makePicture(pickAFile())
  repaint(pic)
  makeGreyscaleThenNegate(pic)
  repaint(pic)

def makeGreyscaleThenNegate(picture):
  for px in getPixels(picture):
    lum=(getRed(px)+getGreen(px)+getBlue(px)/3
    lum=255-lum
    setColor(px,makeColor(lum,lum,lum))

My belief is for this to work,(pic) would already have been named/defined prior to creating the 'driver' function? I just am not sure how (pic) and (picture) are referring to the same file, or am I completely mis-interpreting this..

like image 837
jitterbug Avatar asked Dec 05 '25 10:12

jitterbug


1 Answers

This is really CS101 and nothing Python-specific actually. A function is a name for a code snippet. The names of the variables you pass as arguments to the function and the names of the arguments in the function are totally unrelated, they are just names. What happens in the above snippet:

def driverGrey():
    pic=makePicture(pickAFile())
    # 1. call a function named 'pickAFile' which I assume returne a file or filename
    # 2. pass the file or filename to the function named 'makePicture' which obviously
    #    returns a 'picture' object (for whatever definition of a 'picture object')
    # 3. binds the 'picture object' to the local name 'pic'

    (snip...)

    makeGreyscaleThenNegate(pic)
    # 1. pass the picture object to the function named 'makeGreyscaleThenNegate'.
    #
    #    At that time we enter the body of the 'makeGreyscaleThenNegate' function, 
    #    in which the object known as 'pic' here will be bound to the local 
    #    name 'picture' - IOW at that point we have two names ('pic' and 'picture')
    #    in two different namespaces ('driverGrey' local namespace and
    #    'makeGreyscaleThenNegate' local namespace) referencing the same object.
    #
    # 2. 'makeGreyscaleThenNegate' modifies the object. 
    #
    # 3. when 'makeGreyscaleThenNegate' returns, it's local namespace is destroyed
    #    so we only have the local 'pic' name referencing the picture object,
    #    and the control flow comes back here.

    (snip...)
like image 61
bruno desthuilliers Avatar answered Dec 07 '25 00:12

bruno desthuilliers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!