Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a function call in Python?

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?

like image 850
Hick Avatar asked May 26 '26 00:05

Hick


2 Answers

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.

like image 129
alecxe Avatar answered May 27 '26 13:05

alecxe


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
like image 25
Veedrac Avatar answered May 27 '26 13:05

Veedrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!