python3回调函数_如何使用Python中的回调函数?

I wonder how to correctly use python 2.7 callback functions.

I have some callback functions from Cherrypy auth examples in my code.

(These callbacks return a function that can evaluate to True or False, depending on the logged in user being in a group or not.)

I wonder if a callback is executed or not if I write a piece of code like this:

Given the definition from the library is:

def member_of(groupname):

def check():

if groupname == 'admin':

if cherrypy.request.login == 'joe':

return True

if cherrypy.request.login == 'toni':

return True

return False

return False

# .... (other groups checked in the same way)

return check # returns a callback function from my understanding?

How can I apply and execute the callback in my code?

If I put it like this:

if member_of('admin'):

do_something()

else:

do_something_else()

Will this execute the calllback and check for the admin group? Or will it find out if the value of "member_of" is a function definition and a function definition is probably always a "True" value (or maybe a False value) but both are wrong, because it needs to be executed

Can you enlighten me on this? How can I make sure a callback is executed? An how can I pass it around as it is?

解决方案

In python, like in many other languages, a variable can also contain a function and you can pass them around like other variables that contain e.g. numbers or strings.

CherryPy's member_of function itself does return a function in your example.

I am explaining it in simple steps:

If you write member_of() it returns the result of the function member_of() which is the function with the name check in this case.

cb_function = member_of('admin')

At this point the variable cb_function holds the result of calling the function member_of, and in the last line member_of returns check, which was defined within the function member_of as another function!

You have to call the first result again, because you can and you have to treat it in almost the same way as a local function, that you defined in the current context, to get the final result, by doing something like:

my_result = cb_function()

And then you would continue and use the result. For example you could check its boolean value:

if my_result:

# do something

...

The 3 steps from above together can be written shorter:

cb_function = member_of('admin')

if cb_function():

# do something

...

Or even shorter:

if member_of('admin')():

# do something

...

At first it may appear a little strange in python to have the double ()(), but if you think about it for a while it makes sense.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值