Search code examples
pythonclassoopattributesinstance

How to print all the instances of a class in python?


I want to get all the instances created for a class. Is there any way to get the instances without importing any module ?

I tried this way to append self in a class attribute.

class A(object):
    instances = []

    def __init__(self, foo):
        self.foo = foo
        A.instances.append(self)
        
foo = A("hi")
bar = A("Hey")
star = A("Hero")

for instance in A.instances:
    print("Ins is ",instance)

Output

<__main__.A object at 0x148b8b6e0780>,
<__main__.A object at 0x148b8b6e0780>,
<__main__.A object at 0x148b8b6e0780>

I expect it to print foo,bar,star. Is there any way to get it in class without any module?


Solution

  • you could do the following, if I got you right :

    Proposal

    tmp = globals().copy()
    print(tmp)
    
    for k,v in tmp.items():
        if isinstance(v, A):
            print(k)
    

    You must copy the global variable dictionary, because otherwise i will be changed with the first instantiation in the for-loop:

    Result:

    foo
    bar
    star