简体   繁体   English

Python:轻松打印变量名称和值

[英]Python: print variable name and value easily

I want to use a function that can automatically print out the variable and the value. 我想使用一个可以自动打印出变量和值的函数。 Like shown below: 如下图所示:

num = 3
coolprint(num)

output: 输出:

num = 3

furthermore, it would be cool if it could also do something like this: 此外,如果它也可以做这样的事情会很酷:

variable.a = 3
variable.b = 5
coolprint(vars(variable))

output: 输出:

vars(variable) = {'a': 3, 'b': 5}

Is there any function like this already out there? 那里有没有这样的功能? Or should I make my own? 或者我应该自己做? Thanks 谢谢

An official way to accomplish this task sadly doesn't exist even though it could be useful for many people. 遗憾地完成这项任务的官方方法即使对许多人有用也是不存在的。 What I would suggest and I have used it sometimes in the past is the following(I am not sure if this is the best way to do it). 我建议和过去有时使用过的是以下内容(我不确定这是否是最好的方法)。

Basically what you can do is to create a custom object that mimics one Python's data type per time. 基本上你可以做的是创建一个自定义对象,每次模仿一个Python的数据类型。 Bellow you can find an example for an integer. Bellow你可以找到一个整数的例子。

class CustomVariable(object):

    def __init__(self, name, value):
        self.name = name
        self.value = value

    def __str__(self):
        return "{} = {}".format(self.name, self.value)

    def __add__(self, val) :
        return self.value + val


myVar = CustomVariable("myVar", 15)
print myVar
myVar = myVar + 5
print myVar

Output:
myVar = 15
myVar = 20

Check the special method named "___str____" 检查名为“___str____”的特殊方法

I have discovered the answer is No. There is no way to do this. 我发现答案是否定的。没有办法做到这一点。 However, your best bet is something like this: 但是,你最好的选择是这样的:

from pprint import pprint

def crint(obj, name):

    if isinstance(obj, dict):
        print '\n' + name + ' = '
        pprint(obj)

    else:
        print '\n' + name + ' = ' + str(obj)

that way you can just do: 你可以这样做:

crint(vars(table.content[0]), 'vars(table.content[0])')

or: 要么:

j = 3
crint(j, 'j')

This lambda-based solution works well enough for me, though perhaps not in every case. 这种基于lambda的解决方案对我来说效果很好,但可能并非在所有情况下都如此。 It is very simple and only consumes one line. 它非常简单,只消耗一行。

coolprint = lambda *w: [print(x,'=',eval(x)) for x in w]

Exmaple.. 〔实施例..

coolprint = lambda *w: [print(x,'=',eval(x)) for x in w]

a, *b, c = [1, 2, 3, 4, 5]

coolprint('a')
coolprint('b','c')
coolprint('a','b','c')
coolprint('c','b','b','a','b','c')

which produces.. 生产..

a = 1
b = [2, 3, 4]
c = 5
a = 1
b = [2, 3, 4]
c = 5
a = 1
b = [2, 3, 4]
c = 5
c = 5
b = [2, 3, 4]
b = [2, 3, 4]
a = 1
b = [2, 3, 4]
c = 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM