简体   繁体   中英

How to call Python partial without using parentheses?

Suppose the code below:

from functools import partial
import random

def integer(min=1, max=10):
    return random.randint(min, max)

def double(min=1, max=10):
    return random.uniform(min, max)

if __name__ == '__main__':
    p1 = partial(integer, 5, 10)
    p2 = partial(double, 5, 10)
    for f in [p1, p2]:
        f() # I'd like to know if there's a different way to call this like `call(f)` or something

As mentioned in the comment, I'd like to know if there's a way to call f without using parentheses. One step further, suppose I can call f without using parentheses, if I would like to pass additional parameters to f , how do I go about it (like call(f, additional_param_1, additional_param_2) )?

Thank you in advance for your answers!

Not in base Python, but you can easily write call() yourself:

from functools import partial
import random

def integer(min=1, max=10):
    return random.randint(min, max)

def double(min=1, max=10):
    return random.uniform(min, max)

def call(f, *args, **kwargs):
    return f(*args, **kwargs)

if __name__ == '__main__':
    p1 = partial(integer, 5, 10)
    p2 = partial(double, 5, 10)
    for f in [p1, p2]:
        call(f)

Note: you have a typo in your example, you're calling partial on int , but your function is called integer . (neither is a very good name and I think you're trying to solve a problem that you're not stating, that has a better solution)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM