Reputation: 36394
I've something like this:
import os
from node import Node
def make_sum(num,done):
for i in range(0,100):
num = num + 1
done(num)
def result(num):
print num
return num
node = Node()
node.register(make_sum(20,result))
result(25)
and node.py
is this:
import os
class Node():
def __init__(self):
pass
def register(self,obj):
print obj
What I want to do is this, that the make_sum()
function call should happen from inside the register()
function. But currently it gets called while making the register()
function call.
Is such a thing possible to do it in python, where you can do a forward declaration of a function but call it later?
Upvotes: 3
Views: 383
Reputation: 473833
You can pass make_sum
function as an argument to register
method:
node.register(make_sum, 20, result)
then, call it in the method:
class Node():
def __init__(self):
pass
def register(self, f, num, done):
print f(num, done)
Also, you can use lambda
:
node.register(lambda: make_sum(20, result))
In this case you don't need to pass arguments at all:
class Node():
def __init__(self):
pass
def register(self, f):
print f()
Hope this is what you wanted.
Upvotes: 2
Reputation: 60137
It looks to me like functools.partial
is the more direct way of getting what you want;
from functools import partial
node.register(partial(make_sum, 20,result))
partual(make_sum, 20, result)
makes a new function that, when called, has the arguments 20
and result
automatically added.
It supports *
and **
as well as namd arguments:
loud_printer = partial(print, *(1, 2, 3), end="")
loud_printer
#>>> functools.partial(<built-in function print>, 1, 2, 3, end='')
loud_printer()
#>>> 1 2 3
Upvotes: 1