如何获取传递给Python函数的参数的字面值?
一个Python(3)函数能“知道”传给它的参数的字面值吗?
在下面的例子中,我希望函数listProcessor能够打印出传给它的列表的名字:
list01 = [1, 3, 5]
list02 = [2, 4, 6]
def listProcessor(listName):
"""
Function begins by printing the literal value of the name of the list passed to it
"""
listProcessor(list01) # listProcessor prints "list01", then operates on the list.
listProcessor(list02) # listProcessor prints "list02", then operates on the list.
listProcessor(anyListName) # listProcessor prints "anyListName", et cetera…
我最近才重新开始编程(Python 3)。到目前为止,我尝试的所有方法都只是“解释”了参数,打印出列表的内容,而不是它的名字。所以我怀疑我可能忽略了一些非常简单的方法来“捕捉”传给Python函数的参数的字面值。
另外,在这个例子中,我使用了列表的名字作为参数,但我其实想了解如何捕捉任何类型参数的字面值。
1 个回答
0
虽然有一种叫做自省的东西,可以在某些情况下用来获取变量的名字,但你可能在寻找一种不同的数据结构。如果你把数据放在一个dict
(字典)里,你可以把“标签”放在键里,把“列表”放在值里:
d = { "list01": [1, 3, 5],
"list02": [2, 4, 6] }
def listProcessor(data, key):
print key
print data[key]
listProcessor(d, "list01")