如何在Python中找到一個類別的所有子類別?

Patricia Arquette
發布: 2024-11-15 06:05:02
原創
482 人瀏覽過

How Can I Find All Subclasses of a Class in 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:

  1. Find the class using the class name.
  2. Utilize __subclasses__() to retrieve the subclasses of the located class.

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.

以上是如何在Python中找到一個類別的所有子類別?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板