如何获取类实例的名称?

问题描述 投票:0回答:0

如何获取类实例的名称? 我试过这个...

l=[]
l2=[]
l3=[]
l4=[]

class Rolf():
    def __init__ (self):
        l.append(self)
#        l2.append(*self)    # ERROR: TypeError: list.append() argument after * must be an iterable, not Rolf
        l3.append(str(self))
#        l4.append(str(*self)) # ERRORL TypeError: str() argument after * must be an iterable, not Rolf
        
a = Rolf()
b = Rolf()
c = Rolf()

print(f"1) No of instances= {len(l)}")
print(f"2) List of instances= {l}")
print(f"3) instances are of class type {str(l[0].__class__)}")
print(f"4) for list 'l', Name of each instance= {i for i in l}")
# print(f"5) for list 'l2', Name of each instance= {i for i in l2}")
print(f"6) for list 'l3', Name of each instance= {i for i in l3}")
# print(f"7) for list 'l4', Name of each instance= {i for i in l4}")

l 和 l3 是尝试获取实例的名称(字符串),但仍然显示它们在内存中的对象位置。

那么放入构造函数的正确语法是什么,以便将创建的实例的名称作为字符串保存到列表中?

输出:

1) No of instances= 3
2) List of instances= [<__main__.Rolf object at 0x7f8e3beb3fd0>, <__main__.Rolf object at 0x7f8e3beb39a0>, <__main__.Rolf object at 0x7f8e3beb3970>]
3) instances are of class type <class '__main__.Rolf'>
4) for list 'l', Name of each instance= <generator object <genexpr> at 0x7f8e3be9bca0>
6) for list 'l3', Name of each instance= <generator object <genexpr> at 0x7f8e3be9bca0>
python class instance
© www.soinside.com 2019 - 2024. All rights reserved.