简体   繁体   中英

Literal String substitution in python

Consider the below code snippet in python

argKey = 'actualArgument'

methodA(argKey=argVal) #invoking methodA

where methodA() is defined as :

def methodA(actualArgument, actualArgument2, actualArgument3)

methodA can be invoked only via named arguments ie. you invoke by specifying the argument name and passing the argument value.

--> throws an error :

TypeError: methodA() got an unexpected keyword argument 'argKey '

I want 'methodA' to be invoked by the value contained in the 'argKey' variable ie

methodA(actualArgument=argVal)

How to get the substitution of the string into the method invocation call.?

To pass parameters with computed names, use a dict:

def foo(a, b):
  return a+b

name_of_a = 'a'
params = {name_of_a: 1, 'b': 2}
print foo(**params) # note the asterisks

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