簡體   English   中英

python:如何僅使用字符串名稱將變量傳遞給函數

[英]python: how can I pass a variable to a function with only the string name

我正在與一個相對復雜的程序進行交互,並在其上放置一個GUI來發出命令。 我做了一個簡單的例子,我認為可以說明問題。 我知道發出命令需要傳遞哪些參數,但是我只能將它們作為字符串獲取。

我動態獲得了數百個具有不同返回值的命令,但這是一個示例,當我傳遞命令ID時可以取回

def get_command_vars(commandID = None):
    if commandID == '0x4F':
    return [['mode', '16bits'], ['seconds', '8bits']]


def issueMyCommand(commandID = None):
    commandParameters = get_command_vars(command=0x4F)

commandParameters告訴我此命令的參數是mode和seconds,但它們是字符串

commandParm_1 = commandParameters[0][0] # 'mode'
commandParm_2 = commandParameters[1][0] # 'seconds'

>get User Input from the gui to pass to issuetheCommand
input1 = getinputEntry1() # this is the 'mode' value, e.g., 8
input2 = getinputEntry2() # this is the 'seconds' value, e.g., 14

我有要從用戶輸入傳遞的值,但是我不知道如何將它們傳遞給函數,因為我只有變量作為字符串,即“ mode”和“ seconds”

c = issueTheCommand(mode = input1, seconds = input2)

該命令格式將根據get_command_vars中的參數類型而更改,因此它可能是'count','datalength','milliseconds,'delay'等

@sberry-實際上,用戶輸入值是將通過mode和seconds傳遞的值。 16位和8位在這里並沒有真正發揮作用。 我試圖做到這一點,如果可能的話,不更改“ issueTheCommand”函數期望的格式。 我發出它的方式現在看起來像這樣:c = issueTheCommand(mode = 8,seconds = 14)。 我不認為這會成文嗎?

如果我對您的問題的評論是您要做什么,那么也許使用字典作為關鍵字參數對您有用。

>>> def issueTheCommand(mode, seconds):
...     print mode, seconds
...
>>> issueTheCommand(**{"mode": "16bits", "seconds": "8bits"})
16bits 8bits

指定為關鍵字的參數可以作為字典使用。 相反,關鍵字參數可以作為字典提供。 看:

>>> def a(**b):   # Pick up keyword args in a dict named b.
...   print(b)
... 
>>> a(x=1, y=2)
{'y': 2, 'x': 1}
>>> c = {'y': 2, 'x': 1}
>>> a(**c)
{'y': 2, 'x': 1}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM