简体   繁体   English

在函数中打印变量标签

[英]Printing variable label in function

How would I return a variable name in a function.我将如何在函数中返回变量名。 Eg If I have the function:例如,如果我有这个功能:

def mul(a,b):
   return a*b

a = mul(1,2); a
b = mul(1,3); b
c = mul(1,4); c

This would return:这将返回:

2
3
4

I would like it to return:我希望它返回:

a = 2
b = 3
c = 4

How would I do this?我该怎么做?

Unfortunately, you are unable to go "backwards" and print the name of a variable.不幸的是,您无法“倒退”并打印变量的名称。 This is explained in much further detail in this StackOverflow post .这在StackOverflow 帖子中有更详细的解释。

What you could do is put the variable names in a dictionary.您可以做的是将变量名称放入字典中。

dict = {"a":mul(1,2), "b":mul(1,3), "c":mul(1,4)}

From there you could loop through the keys and values and print them out.从那里你可以遍历键和值并将它们打印出来。

for k, v in dict.items():
    print(str(k) + " = " + str(v))

Alternatively, if you wanted your values ordered, you could put the values into a list of tuples and again loop through them in a for loop.或者,如果您希望对值进行排序,则可以将这些值放入一个元组列表中,然后再次在 for 循环中遍历它们。

lst = [("a", mul(1,2)), ("b", mul(1,3)), ("c",mul(1,4))]

Here is how to do it with python-varname package:以下是如何使用python-varname包执行此操作:

from varname import varname

def mul(a, b):
   var = varname()
   return f"{var} = {a*b}"

a = mul(1,2)
b = mul(1,3)
c = mul(1,4)

print(a) # 'a = 2'
print(b) # 'b = 2'
print(c) # 'c = 2'

The package is hosted at https://github.com/pwwang/python-varname .该包托管在https://github.com/pwwang/python-varname

I am the author of the package.我是包的作者。 Let me know if you have any questions using it.如果您对使用它有任何疑问,请告诉我。

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

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