我知道你不应该在程序中使用变量名,但我使用的是严格的调试目的,并希望将变量的名称传达给用户以提高可读性。
我有一个这样的文件:
class MyClass(object):
def __init__(self):
pass
def foo(msg=""):
debug("Called from the %s instance.") #quazi-print function that only prints when a DEBUG variable is True.
print(msg)
m = MyClass()
m.foo("Test")
Run Code Online (Sandbox Code Playgroud)
我想m从类本身中检索实例变量名称。虽然这只是一个示例文件,但我使用它向用户传达已在实例变量中的某个属性处创建了原始套接字,并希望显示它的位置(即New socket at m.socket)
这对 Python 可行吗?
我有这个代码:
我稍微重申了问题的表述.不确定礼仪是否要发布新问题.如果是这样,我的坏
import numpy as np
a = np.array([0,0])
b = np.array([1,0])
c = np.array([2,0])
my_array_list = [a,b,c]
for my_array in my_array_list:
np.save('string_that is representative of my_array',my_array)
Run Code Online (Sandbox Code Playgroud)
其中'代表我的数组的字符串'等于'a','b','c'或类似字符.
可能有更好的方法来解决这个问题,我现在就想不出来.
快速有效地做到这一点的最佳方法是什么?
我想应该已经有这样的问题了,但是我还没有找到。这可能是因为我不知道我正在寻找的确切概念/单词,但这里是一个例子:
我有这个代码:
group_1 = ['Hello', 'world', '!']
group_2 = [1,23,4,2,5,2]
group_3 = ['A', 'K', 'L']
all_groups = [group_1, group_2, group_3]
for i in all_groups:
print(i, ':', len(i))
Run Code Online (Sandbox Code Playgroud)
它给出了这个输出:
['Hello', 'world', '!'] : 3
[1, 23, 4, 2, 5, 2] : 6
['A', 'K', 'L'] : 3
Run Code Online (Sandbox Code Playgroud)
这是预期的输出:
'group_1' : 3
'group_2' : 6
'group_3' : 3
Run Code Online (Sandbox Code Playgroud)
group_1正如您所看到的,我正在尝试打印可调用对象、group_2和 的名称group_3。有什么建议么?
说我已经定义了这些变量
a=1
b="2"
c=2
d=2
e="2"
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来获取可以与我指定的对象配对的所有变量名称.例如,如果我指定"2",它应返回["b","e"],因为它们是值为"2"的两个变量.如果我指定整数2,它应该给我["c","d"].有没有办法做到这一点?我也在寻找一个pythonic答案.