你如何在一个类中使用闭包 [英] how do you use a closure in a class

查看:72
本文介绍了你如何在一个类中使用闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个函数在一个类中几乎相同我会想要使用一个闭包去除额外的代码我将如何做到这一点?

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?

推荐答案

嗯,我不确定封闭是什么?是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, you
can use functions to dynamically create other functions. Here''s an
example of this feature (although there are far simpler ways to do
this), tallying vowels and consonants in an input string by calling a
function looked up in a dictionary. Note that tallyFn creates a
temporary function that uses the ''key'' argument passed into tallyFn,
and then returns the temporary function. Perhaps this idiom can serve
in 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 structure
tally = {}
tally["consonant"] = 0
tally["vowel"] = 0
tally["not sure"] = 0
tally["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 functions
functions = {}
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 tally

Gives:
{''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, you
can use functions to dynamically create other functions. Here''s an
example of this feature (although there are far simpler ways to do
this), tallying vowels and consonants in an input string by calling a
function looked up in a dictionary. Note that tallyFn creates a
temporary function that uses the ''key'' argument passed into tallyFn,
and then returns the temporary function. Perhaps this idiom can serve
in 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 structure
tally = {}
tally["consonant"] = 0
tally["vowel"] = 0
tally["not sure"] = 0
tally["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 functions
functions = {}
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 tally

Gives:
{''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 a
pedagogically-meaningful example, all that typing makes me
wonder what lesson we''re teaching. To me, it''s more in the
spirit of python to have a

if c in "aeiou":
...
elif c in "bcdfghjklmnpqrstvwxz":
...
elif c == "y":
...

in there somewhere. What am I missing about your dictionary
construction?

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 message
news: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?




一个更具体的例子可能会得到更多的解决方案;-)


TJR



A more specific example might get a more to the point solution ;-)

TJR


这篇关于你如何在一个类中使用闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆