How To Use A Callback Function In Python?
Solution 1:
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')
ifcb_function():
# do something
...
Or even shorter:
ifmember_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.
Solution 2:
If you execute it, it is plain simple.
member_of()
will return method object check.
you have to execute to get result by doing something like if member_of('admin')()
:
or,
k=member_of('admin')
ifk():
To do your task.
Post a Comment for "How To Use A Callback Function In Python?"