简体   繁体   中英

Is there a way to define a PYthon function parameter list by a string?

Is it possible to define a Python function parameter list by a string like the following?:

param_list = "alpha, beta = 100, *args"

def my_func(param_list):
   return 100

不,没有合理的方法可以做到这一点。

If you, for some reason, want to be able to redefine the function parameters using a string, you can do it, but it'd require using eval() and string formatting.

Shorthand example:

#since you can do:
def a():
    return 1

def b():
    return 2

a = b
#a() returns 2 now, because calls to a() are actually calls to b() now

#you can also do:
a = eval("def a({str_of_args}): \n    return 3")

#a(proper arguments) now returns 3

Having said that, I cannot think of any case where this would actually be a good idea . It's an ugly hack 99.9% of the time, and if you HAVE to do that, it should be taken as a sign something is likely seriously wrong with the design as a whole.

I believe you would need to split the string and read the 'parameters'. There is no way for python to translate your string to parameters. Guess you could use eval... but its ugly.

What you could do is build a string

"my_func(alpha, beta = 100, *args)"

and eval it:

eval("my_func(alpha, beta = 100, *args)")

You can also do this:

my_func(eval("alpha, beta = 100, *args"))

However, you may want to make changes to your function because this will give you an error as is.

If you are passing a variable number of objects, use args that is what it is there for.

You can pass variable number of parameters like this:

def someMethod(*listOfStringParameters):
    for i in listOfStringParameters:
        print(i)

someMethod("alpha", "beta", "gamma", "delta")

Output:

alpha
beta
gamma
delta

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