简体   繁体   中英

How to use introspection in Python 2.7 to find instances of certain class in a module?

I have a Python module that defines a classes and instantiates a number of instances of that classes. I would like to write a test that the correct number have been instantiated.

bar = Foo('abc')
baz = Foo('def')
...
quz = Foo('xyz')

Then in testing I have tried things like:

assert num = len([ x for x in dir(foo) if isinstance(x, foo.Foo)])    

which doesn't work, because dir(foo) seems to give a list of Strings.

Is there a way to find the instances of a particular class in a module?

You're really close. Use a double equals sign for comparison, and you need to use getattr() to retrieve the module member by name:

assert num == len([getattr(foo, x) 
                   for x in dir(foo) 
                   if isinstance(getattr(foo, x), foo.Foo)])

Might also be helpful to read the documentation on dir() .

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