Home > Backend Development > Python Tutorial > How can I find the subclasses of a given class in Python?

How can I find the subclasses of a given class in Python?

DDD
Release: 2024-11-16 01:39:03
Original
958 people have browsed it

How can I find the subclasses of a given class in Python?

Finding Subclasses of a Class in Python

In Python, you can determine the subclasses of a given class through its __subclasses__() method. This method is available to new-style classes, which are inherited from the "object" class and are commonly used in Python 3.

To obtain the names of the subclasses:

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

[cls.__name__ for cls in Foo.__subclasses__()]
# ['Bar', 'Baz']
Copy after login

Alternatively, to retrieve the subclasses themselves:

Foo.__subclasses__()
# [<class '__main__.Bar'>, <class '__main__.Baz'>]
Copy after login

To confirm the base class association:

for cls in Foo.__subclasses__():
    print(cls.__base__)
# <class '__main__.Foo'>
# <class '__main__.Foo'>
Copy after login

Recursive Subclass Retrieval:

If you need to capture subsubclasses (grandchildren, etc.), a recursive approach is necessary:

def all_subclasses(cls):
    return set(cls.__subclasses__()).union(
        [s for c in cls.__subclasses__() for s in all_subclasses(c)])

all_subclasses(Foo)
# {<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>}
Copy after login

Note: If a subclass's class definition has not been executed (e.g., its module is not imported), it won't be detectable by __subclasses__().

Obtaining Subclasses from a Class Name:

Suppose you have the class name as a string instead. In that case, follow these steps:

  1. Find the class object using the class name:

    • If in the same module:

      cls = globals()[name]
      Copy after login
    • If in any module:

      import importlib
      modname, _, clsname = name.rpartition('.')
      mod = importlib.import_module(modname)
      cls = getattr(mod, clsname)
      Copy after login
  2. Use __subclasses__() to obtain the subclasses of the retrieved class object.

The above is the detailed content of How can I find the subclasses of a given class in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template