简体   繁体   中英

how to find instances of a class at runtime in python

how to find instances of a class at runtime in python

eg.

class Foo():
    pass

class Bar(Foo):
    def __init__(self, a):
            print a

inst_b1 = Bar(3)
inst_b2 = Bar('Hello World!!!')

How would i find out how many instances of class Bar exists and there names at runtime?

Also, as i want to use them at runtime what would be the better solution to have them in a custom dict or get it from the universal dict of variables(using vars()).

Thanks

class Bar(Foo):
    instances = []
    def __init__(self, a):
            print a
            Bar.instances.append(self)

inst_b1 = Bar(3)
inst_b2 = Bar('Hello World!!!')
print len(Bar.instances)
print Bar.instances

Its much more complicated to get the variable name you assigned to it...

How many can be done thus:

import gc
n_Bars = sum(1 for obj in gc.get_objects() if isinstance(obj,Bar))

If you also want their names, you may be better off using a dict instead of separate variables.

Edit: I just thought of a hack to get the names too:

for obj_name in dir():
    if isinstance(eval(obj_name), Bar):
        print obj_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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