简体   繁体   中英

Python - Pass default values for arguments that are function of other arguments of the function

I would like to write a function in which the default value of one argument is a function of some arguments that are being passed to the same function. Something like this:

def function(x, y = function2(x)):
    ##definition of the function

Is it possible to write such a function in Python? I came across this answer for c++. But there is no method overloading in Python

Thanks in advance.

A pretty usual way of solving this is by using None as a placeholder:

def function(x, y=None):
    if y is None:
        y = f2(x)

    pass  # whatever function() needs to do

This makes no sense. hat are you trying to achieve? What is the Y? Is taht function? then you must write:

def function(x, y = function2):
    ##definition of the function

If the Y is a simple value then you must write:

def function(x, y = None):
    if y is None:
         y = function2(x)

I don't know what exactly are you trying to achieve here use case wise but you can use a decorator that does what is required for you.

A silly example is here https://repl.it/@SiddharthShishu/IntrepidPunctualProspect

def function(x, y=None):
    if y is None:
        y = f2(x)

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