I have several functions that are almost the same in one class I wouldlike to use a closure to get rid of the extra code how would I do this?推荐答案嗯,我不确定封闭是什么?是Pythonic的方式。但是在Python中,你可以使用函数来动态创建其他函数。这里有一个 这个功能的例子(尽管有更简单的方法可以做到这一点),通过调用一个输入字符串来计算输入字符串中的元音和辅音。 /> 函数在字典中查找。请注意,tallyFn创建一个 临时函数,该函数使用传递给tallyFn的''key''参数, 然后返回临时函数。也许这个成语可以用来代替你对小型匿名函数的闭包概念。 - Paul (用空格替换领先的。'我用Google网上论坛发帖): #global tally structure tally = { } tally [" consonant"] = 0 tally [" vowel"] = 0 tally [" not sure" ] = 0 tally [" none"] = 0 #函数构造其他函数(而不是闭包) def tallyFn(key): ..... def addToTally(): ......... tally [key] = tally [key ] + 1 .....返回addToTally #创建函数字典 functions = {} 函数[" a"] = tallyFn(" vowel") 函数[" b"] = tallyFn("辅音") 函数[" c] = tallyFn(辅音) 函数[" d" ] = tallyFn(辅音) 函数[" e] = tallyFn(元音) 函数[" f"] = tallyFn( 辅音) 函数[" g"] = tallyFn("辅音") 函数[" h"] = tallyFn(" consonant" ) 函数["]"] = tallyFn(" vowel") 函数[" j"] = tallyFn(" consonant") 函数[" k"] = tallyFn(" consonant") 函数[" l"] = tallyFn(" consonant") 函数[" m] = tallyFn(辅音) 函数[" n"] = tallyFn("辅音") 函数[" ; o"] = tallyFn(" vowel") 函数[" p"] = tallyFn("辅音") 函数[" q"] = tallyFn(辅音) 函数[" r"] = tallyFn(" consonant") 函数[" s"] = tallyFn(" consonant") 函数[" t"] = tallyFn(" consonant") 函数[" u] = tallyFn(元音) 函数[" v"] = tallyFn(" consonant") 函数[" w"] = tallyFn(辅音) 函数[" x"] = tallyFn(" consonant") 函数[" y"] = tallyFn("不确定) 函数[" z"] = tallyFn(" consonant") 函数[" "] = tallyFn(" none") 函数[""] = tallyFn(" none") testdata =" ;" 快速的棕色狐狸跳过懒狗。 现在是所有好男人来的时间。 许多人的手工作很轻。 """ for testdata.split(" \ n"): .....对于c in line.lower(): ......... fn =函数[c] ......... fn() 打印统计 给: {''none'':26,''辅音'':59,''不确定'':3,''元音'':33}Well, I''m not sure "closure" is the Pythonic way. But in Python, youcan use functions to dynamically create other functions. Here''s anexample of this feature (although there are far simpler ways to dothis), tallying vowels and consonants in an input string by calling afunction looked up in a dictionary. Note that tallyFn creates atemporary function that uses the ''key'' argument passed into tallyFn,and then returns the temporary function. Perhaps this idiom can servein place of your concept of closures for small anonymous functions.-- Paul(replace the leading .''s with spaces - I''m posting with Google Groups):# global tally structuretally = {}tally["consonant"] = 0tally["vowel"] = 0tally["not sure"] = 0tally["none"] = 0# function to construct other functions (instead of closures)def tallyFn( key ):.....def addToTally():.........tally[key] = tally[key] + 1.....return addToTally# create dict of functionsfunctions = {}functions["a"] = tallyFn("vowel")functions["b"] = tallyFn("consonant")functions["c"] = tallyFn("consonant")functions["d"] = tallyFn("consonant")functions["e"] = tallyFn("vowel")functions["f"] = tallyFn("consonant")functions["g"] = tallyFn("consonant")functions["h"] = tallyFn("consonant")functions["i"] = tallyFn("vowel")functions["j"] = tallyFn("consonant")functions["k"] = tallyFn("consonant")functions["l"] = tallyFn("consonant")functions["m"] = tallyFn("consonant")functions["n"] = tallyFn("consonant")functions["o"] = tallyFn("vowel")functions["p"] = tallyFn("consonant")functions["q"] = tallyFn("consonant")functions["r"] = tallyFn("consonant")functions["s"] = tallyFn("consonant")functions["t"] = tallyFn("consonant")functions["u"] = tallyFn("vowel")functions["v"] = tallyFn("consonant")functions["w"] = tallyFn("consonant")functions["x"] = tallyFn("consonant")functions["y"] = tallyFn("not sure")functions["z"] = tallyFn("consonant")functions[" "] = tallyFn("none")functions["."] = tallyFn("none")testdata = """The quick brown fox jumps over the lazy dog.Now is the time for all good men to come to.Many hands make light work heavy."""for line in testdata.split("\n"):.....for c in line.lower():.........fn = functions[c].........fn()print tallyGives:{''none'': 26, ''consonant'': 59, ''not sure'': 3, ''vowel'': 33}在文章< 11 ********************** @ l41g2000cwc.googlegroups .com> ;, Paul McGuire< pt***@austin.rr.com>写道:In article <11**********************@l41g2000cwc.googlegroups .com>,Paul McGuire <pt***@austin.rr.com> wrote:嗯,我不确定封闭是什么是Pythonic的方式。但在Python中,您可以使用函数动态创建其他函数。这里有一个这个功能的例子(尽管有更简单的方法可以做到这一点),通过调用函数在字典中查找元音和辅音查找字典。请注意,tallyFn创建一个临时函数,该函数使用传入tallyFn的key参数,然后返回临时函数。也许这个成语可以代替你对小型匿名函数的闭包概念。 - Paul (用空格替换领先的。) - 我正在发布Google群组): #global tally structure tally = {} tally [" consonant"] = 0 tally [ vowel] = 0 tally [" not sure"] = 0 tally [" none"] = 0 构造其他函数的函数(代之以of closures) def tallyFn(key): .... def addToTally(): ........ tally [key] = tally [key] + 1 ....返回addToTally #create of functions functions = {} functions [" a"] = tallyFn(" vowel")函数[" b"] = tallyFn(" consonant")函数[" c"] = tallyFn(" consonant")函数[" d"] = tallyFn (辅音)函数[" e] = tallyFn(元音)函数[" f"] = ta llyFn(辅音)函数[" g] = tallyFn(辅音)函数[" h] = tallyFn(辅音)函数[i] = tallyFn(vowel)函数[j] = tallyFn(辅音)函数[" k"] = tallyFn("辅音") ;)函数[l] = tallyFn(辅音)函数[" m] = tallyFn(辅音)函数[" n] ] = tallyFn(辅音)函数[o] = tallyFn(元音)函数[" p"] = tallyFn(" consonant") functions [" q"] = tallyFn(" consonant")函数[" r"] = tallyFn(" consonant")函数[" s"] = tallyFn(" ;辅音)函数[t] = tallyFn(辅音)函数[" u]] = tallyFn(元音)函数["] v"] = tallyF n(辅音)函数[" w] = tallyFn(辅音)函数[" x] = tallyFn(辅音)函数[y] = tallyFn(不确定)函数[" z] = tallyFn(辅音)函数[" "] = tallyFn(" none")函数[""] = tallyFn(" none") testdata =""" 快速的棕色狐狸跳过懒狗。现在是所有好人来的时候了。许多人轻松工作。""" for test in testdata.split(" \ n"): .... for c in line.lower(): ........ fn =函数[c] ........ fn() 打印理货 Gives: {''none' ':26,''辅音'':59,''不确定'':3,''元音'':33}Well, I''m not sure "closure" is the Pythonic way. But in Python, youcan use functions to dynamically create other functions. Here''s anexample of this feature (although there are far simpler ways to dothis), tallying vowels and consonants in an input string by calling afunction looked up in a dictionary. Note that tallyFn creates atemporary function that uses the ''key'' argument passed into tallyFn,and then returns the temporary function. Perhaps this idiom can servein place of your concept of closures for small anonymous functions.-- Paul(replace the leading .''s with spaces - I''m posting with Google Groups):# global tally structuretally = {}tally["consonant"] = 0tally["vowel"] = 0tally["not sure"] = 0tally["none"] = 0# function to construct other functions (instead of closures)def tallyFn( key ):....def addToTally():........tally[key] = tally[key] + 1....return addToTally# create dict of functionsfunctions = {}functions["a"] = tallyFn("vowel")functions["b"] = tallyFn("consonant")functions["c"] = tallyFn("consonant")functions["d"] = tallyFn("consonant")functions["e"] = tallyFn("vowel")functions["f"] = tallyFn("consonant")functions["g"] = tallyFn("consonant")functions["h"] = tallyFn("consonant")functions["i"] = tallyFn("vowel")functions["j"] = tallyFn("consonant")functions["k"] = tallyFn("consonant")functions["l"] = tallyFn("consonant")functions["m"] = tallyFn("consonant")functions["n"] = tallyFn("consonant")functions["o"] = tallyFn("vowel")functions["p"] = tallyFn("consonant")functions["q"] = tallyFn("consonant")functions["r"] = tallyFn("consonant")functions["s"] = tallyFn("consonant")functions["t"] = tallyFn("consonant")functions["u"] = tallyFn("vowel")functions["v"] = tallyFn("consonant")functions["w"] = tallyFn("consonant")functions["x"] = tallyFn("consonant")functions["y"] = tallyFn("not sure")functions["z"] = tallyFn("consonant")functions[" "] = tallyFn("none")functions["."] = tallyFn("none")testdata = """The quick brown fox jumps over the lazy dog.Now is the time for all good men to come to.Many hands make light work heavy."""for line in testdata.split("\n"):....for c in line.lower():........fn = functions[c]........fn()print tallyGives:{''none'': 26, ''consonant'': 59, ''not sure'': 3, ''vowel'': 33} 帮助我。虽然我认识到你正在构建一个教学上有意义的例子,但所有打字都让我想起了我们在教什么课。对我来说,如果c在aeiou中的话,那么在蟒蛇的精神上就更有价值了: : ... elif c inbcdfghjklmnpqrstvwxz: ... elif c ==" y": ...... 在某处。关于你的字典我错过了什么 构造? 我很难重复输入相同的变量引用。Help me. While I recognize you''re looking to construct apedagogically-meaningful example, all that typing makes mewonder what lesson we''re teaching. To me, it''s more in thespirit of python to have aif c in "aeiou":...elif c in "bcdfghjklmnpqrstvwxz":...elif c == "y":...in there somewhere. What am I missing about your dictionaryconstruction?It''s hard for me to type the same variable reference repeatedly. < er ********* @ gmail.com>在消息中写道 news:11 ********************** @ o13g2000cwo.googlegr oups.com ...<er*********@gmail.com> wrote in messagenews:11**********************@o13g2000cwo.googlegr oups.com...我有几个函数在一个类中几乎相同我会喜欢使用闭包来摆脱额外的代码我该怎么做?I have several functions that are almost the same in one class I would like to use a closure to get rid of the extra code how would I do this? 一个更具体的例子可能会得到更多的解决方案;-) TJRA more specific example might get a more to the point solution ;-)TJR 这篇关于你如何在一个类中使用闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-23 06:25