私はこれを読んでいました。wonderful pieceは、デコレータをPythonで説明しようとしています。Pythonデコレータで別の関数に渡されたときの変数の範囲
私の質問はこのコードスニペットに固有です。私は理解していない何
def surround_with(surrounding):
"""Return a function that takes a single argument and."""
def surround_with_value(word):
return '{}{}{}'.format(surrounding, word, surrounding)
return surround_with_value
def transform_words(content, targets, transform):
"""Return a string based on *content* but with each occurrence
of words in *targets* replaced with
the result of applying *transform* to it."""
result = ''
for word in content.split():
if word in targets:
result += ' {}'.format(transform(word))
else:
result += ' {}'.format(word)
return result
markdown_string = 'My name is Jeff Knupp and I like Python but I do not own a Python'
markdown_string_italicized = transform_words(markdown_string, ['Python', 'Jeff'],
surround_with('*'))
print(markdown_string_italicized)
は(transform_words()
内transform(word)
によって渡さ時)機能surround_with()
はそれのスコープ内の変数word
を手に入れた方法ですか?私は、周囲の値が何でなければならないのか(関数の引数として)保持変数だけを宣言したことを意味します。 word
はどのようにして入手できますか?
私はここで何が欠けていますか?私はそれを理解だと思う
'transform_words 'の中で、関数' surround_with_value' **は** 'transform'です。実際には 'surround_with_value'が' surround_with_value(word) 'のスコープから外れてしまうので、実際には' surround_with_value(word) 'を呼び出すことになります。 '終わりですが、これはこれを考えるのが一番簡単な方法です)*。 – jonrsharpe
@jonrsharpeそれは意味がある、私は私の理解に基づいて答えを投稿した、あなたはその正当性をチェックできますか? –