Rumah > Artikel > pembangunan bahagian belakang > Bagaimanakah Saya Boleh Cari Semua Subkelas Kelas dalam Python?
Finding All Subclasses of a Class in Python
To retrieve all classes inherited from a specified base class in Python, utilize the __subclasses__() method. This method is available for new-style classes that extend the object class (the default in Python 3). Here's how it works:
class Foo(object): pass class Bar(Foo): pass class Baz(Foo): pass class Bing(Bar): pass print([cls.__name__ for cls in Foo.__subclasses__()]) # ['Bar', 'Baz'] print(Foo.__subclasses__()) # [<class '__main__.Bar'>, <class '__main__.Baz'>]
To include subsubclasses, recursion can be used:
def all_subclasses(cls): return set(cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in all_subclasses(c)]) print(all_subclasses(Foo)) # {<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>}
Note: Subclasses that have not been defined yet (e.g., due to unimported modules) will not be detected by __subclasses__().
Locating Subclasses Using a Class Name String:
When only the class name is available as a string, the following steps are necessary:
Finding a Class from a Name String:
The method for locating a class from a name string depends on its expected location:
If expected within the same module:
cls = globals()[name]
If expected within the locals namespace:
cls = locals()[name]
If anywhere in the modules:
import importlib modname, _, clsname = name.rpartition('.') mod = importlib.import_module(modname) cls = getattr(mod, clsname)
Once the class is found, its __subclasses__() method can be used to retrieve the desired list of subclasses.
Atas ialah kandungan terperinci Bagaimanakah Saya Boleh Cari Semua Subkelas Kelas dalam Python?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!