bluesummers
bluesummers

Reputation: 12607

List all inner classes of a given class - Python

Given a class, how would I list all of its inner classes?

class Car:
    some_var = "var"

    class Engine:
        some_other_var = "var2"

    class Body:
        another_var = "var3"

Now given Car I want to be able to list or iterate over all of its inner classes (Engine, Body)

(Python 3.5)

Upvotes: 2

Views: 1491

Answers (1)

Anthony Kong
Anthony Kong

Reputation: 40634

You can do something like this:

import inspect
[d for d in dir(Car) if inspect.isclass(getattr(Car, d))]

It will give you a list of Class in your class Car.

Be mindful, variable d is a string

Upvotes: 5

Related Questions