python对象列表get object not value?

2024-10-01 15:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

微不足道的例子:

a = 1
b = 2
c = 3
rrr = []
rrr.append(a)
rrr.append(b)
rrr.append(c)
rrr

退货:

[1,2,3]

但我需要得到:

[a,b,c]

我见过这个:

How can I get the name of an object in Python?

但我不太确定解决方案是不是说只有函数才有__name__属性。你知道吗

我要解决的问题是我有一个类,它的一个属性是它拥有的其他属性的列表,所以我可以很容易地遍历它们(它们经常在一起,而且都是布尔值)。但是我需要检查一下这个列表,它抓住的是它的名字,而不是它的值。你知道吗

列表不应该先指向变量,然后再指向变量引用的值吗?或者python在本例中只是跳过了变量的post-it注释,而只是查看实际对象吗?你知道吗

如果是这样的话,在构建列表的过程中,是否有必要强制它走很长的路,查看post-it-note变量,以便我可以恢复它们?你知道吗


Tags: ofthenamean列表get属性it
1条回答
网友
1楼 · 发布于 2024-10-01 15:29:03

您可以尝试:

class MyIntValue:
    def __init__(self, x:int, name:str):
        self.name = name
        self.value = x

    def __repr__(self):
        return self.name


a = MyIntValue(1, 'a')
b = MyIntValue(2, 'b')
c = MyIntValue(3, 'c')
rrr = []
rrr.append(a)
rrr.append(b)
rrr.append(c)

print(rrr)

输出:

[a, b, c] 

相关问题 更多 >

    热门问题