![](/img/trans.png)
[英]Python - can we use value of a variable as a part of the name of a different variable
[英]How can we print the variable name along with its value in python, which will be useful during debugging?
我多次寫過類似的東西:
print 'customer id: ', customerId
我想有一個函數,它打印變量名稱和值
>>myprint(customerId)
>>customerId: 12345
完全按照你的需要進行符號表中的O(n)查找,這很糟糕恕我直言。
如果可以傳遞與變量名對應的字符串,則可以執行以下操作:
import sys
def myprint(name, mod=sys.modules[__name__]):
print('{}: {}'.format(name, getattr(mod, name)))
測試:
a=535
b='foo'
c=3.3
myprint('a')
myprint('b')
myprint('c')
將打印:
a: 535
b: foo
c: 3.3
您也可以通過傳遞第二個參數來使用它來打印來自另一個模塊的變量,例如:
>>> import os
>>> myprint('pathsep', os)
pathsep: :
基本上,每次調用它時都需要將變量名稱手工輸入到輔助函數的參數中,這與將字符串直接格式化為打印消息的方式相同。
另一個可能的(無用的?)heck可以是以下內容:
import re
regex = re.compile("__(.+)")
def check_value(checkpoint_name):
print "============"
print checkpoint_name
print "============"
for variable_name, variable_value in globals().items():
if regex.match(variable_name) is None:
print "%s\t:\t%s" % (variable_name, str(variable_value))
print "============"
,在每次調用的全局范圍內打印所有非系統保護的聲明變量。 要調用該函數,請執行
a = 0
check_value("checkpoint after definition of a")
b = 1
check_value("checkpoint after definition of b")
您可以根據需要自定義功能。 我想出了這個,不知道這是否按你想要的方式工作......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.