3

私はPythonを初めて使用し、コマンドラインに入力せずに関数を実行するための「ドライバー」を表示されました。

ドライバーの概念や正しく入力する方法がわかりません。ドライバーの使用方法に関するフィードバックをお待ちしております。

私が理解していないのは、関数 makeGreyscaleThenNegate(pic) を入力して def 関数 makeGreyscaleThenNegate(picture) を呼び出す方法です: 入力値が (pic) と (picture) で異なる場合。(これは、「ドライバー」機能がどのように機能するかを知らないためだと思います。)

これが私が見せられたものです

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))

私の信念は、これが機能することです.(pic)は、「ドライバー」関数を作成する前にすでに名前が付けられている/定義されているでしょうか? (pic) と (picture) がどのように同じファイルを参照しているのか、またはこれを完全に誤解しているのか、よくわかりません..

4

2 に答える 2

1

これは実際には CS101 であり、実際には Python 固有のものではありません。関数は、コード スニペットの名前です。関数に引数として渡す変数の名前と、関数内の引数の名前はまったく無関係であり、単なる名前です。上記のスニペットで何が起こるか:

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...)
于 2013-09-27T07:20:25.403 に答える
0

picpictureは単なる名前またはラベルです。データのチャンクは、好きなように呼び出すことができます。たとえば、スペイン人は牛乳のボトルを「レチェ」と呼びますが、フランス人は「レイト」と呼びます。

同じことが Python にも当てはまります。ある種の「画像」オブジェクトがあり、プログラム全体で、それをさまざまな名前で呼び出しています。driverGray関数ではそれpicを と呼び、関数makeGrayscaleThenNegateでは画像と呼びます。別の名前、同じオブジェクト。

私がこれを行うとしたら:

pic = makePicture(pickAFile())
b = pic
c = b

... picb、およびの両方cがまったく同じ「もの」を参照しています。bのようなことをして を変更すると、 とb.var = 13の両方も変更されます。cpic

(注: のようなことをした場合、それは画像オブジェクトではなく数値を意味するようになったc = 1と言っています。および変数は影響を受けません。cpicb

ここに比喩があります。もし誰かが牛乳に毒を入れたとしても、スペイン人やフランス人がその牛乳を何と呼んでいようと関係ありません。特定の名前に関係なく、毒が入っています。


あなたの場合、makeGreyscaleThenNegate(pic)最初の関数内で行うと、画像オブジェクトを「渡す」と言っています(たまたま呼び出しますpic)。makeGrayscaleThenNegate関数は として定義されますdef makeGreyscaleThenNegate(picture):。これは、渡された最初の引数が、その関数の期間中「picture」と呼ばれることを意味します。

于 2013-09-27T07:21:47.803 に答える