我已经多次写过这样的东西:
print 'customer id: ', customerId
我想要一个打印变量名和值的函数
>>myprint(customerId)
>>customerId: 12345
我已经多次写过这样的东西:
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: :
基本上,每次调用它时,您都需要将变量名称手动输入到辅助函数的参数中,这与直接将字符串格式化为打印消息相同。
另一种可能的(没用的?)见鬼的可能是:
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")
随意根据您的需要自定义功能。我只是想出了这个,不确定这是否按你想要的方式工作......