是否可以使用一串变量名作为函数的输入?

问题描述 投票:0回答:1

我想知道的是这样的事情是否可行(下面的Python代码)

def my_function(v1, v2):
    return v1+v2

var1 = 1
var2 = 2

vars = "var1,var2"

print(my_function(vars))

我知道这段代码将不起作用,因为该函数需要两个参数,但是我想知道的原因是我想设计一个可以更改参数长度的函数。 * args和** kwargs将不起作用,因为我正在调用的函数已经生成。这是我的上下文代码段

def construct_transaction(value, chain_id, gas, gas_price, **params):

    # amountIn = w3.toWei(0.1, 'ether')   # << These are the variables I would like to 
    # amountOutMin = 1                    # input into the function below
    # path = [token_0_addr, token_1_addr] # "swapExactTokensForTokens"
    # to_addr = my_addr
    # deadline = 1690528847

    for key in params.keys():
        locals()[key] = params[key]       # variables created from params

    nonce = w3.eth.getTransactionCount(w3.toChecksumAddress(my_addr))

    txn = uniswap_v2_router_contract.functions.swapExactTokensForTokens("amountIn,..,"). \
        buildTransaction({
        'value': 0,
        'chainId': chain_id,
        'gas': gas,
        'gasPrice': gas_price,
        'nonce': nonce,
    })

参数的数量将根据所调用的协定和函数而变化。预先感谢。

python function ethereum smartcontracts web3
1个回答
0
投票

您可以将函数存储在dict中,以按名称访问它们,然后将参数传递为*args

def execute_fun(my_funs: dict, name: str, args: tuple):
    """
    lookup a function by name from my_funs dict and execute it using the provided args
    """
    return my_funs[name](*args)

def first_fun(a):
    return a + a

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

my_funs = {
    'first_fun': first_fun,
    'second_fun': second_fun
}

execute_fun(my_funs, 'first_fun', (7,)) # 14
execute_fun(my_funs, 'second_fun', (4, 5,)) # 9

不过,使用类和getattr可能会更好地完成此[[looks。

© www.soinside.com 2019 - 2024. All rights reserved.