亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中,如何獲取特定文件中定義的類列表?

在 Python 中,如何獲取特定文件中定義的類列表?

料青山看我應如是 2021-11-30 16:45:58
如果文件myfile.py包含:class A(object):  # Some implementationclass B (object):  # Some implementation我如何定義一個方法,以便在給定的myfile.py情況下返回 [A, B]?這里,A 和 B 的返回值可以是類的名稱或類的類型。(i.e. type(A) = type(str) or type(A) = type(type))
查看完整描述

3 回答

?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

您可以同時獲得:

import importlib, inspect
for name, cls in inspect.getmembers(importlib.import_module("myfile"), inspect.isclass):

您可能還想檢查:

if cls.__module__ == 'myfile'


查看完整回答
反對 回復 2021-11-30
?
當年話下

TA貢獻1890條經驗 獲得超9個贊

萬一它幫助別人。這是我使用的最終解決方案。此方法返回在特定包中定義的所有類。


我將 X 的所有子類保存在特定文件夾(包)中,然后,使用此方法,我可以加載 X 的所有子類,即使它們尚未導入。(如果它們尚未導入,則無法通過 訪問它們__all__;否則事情會容易得多)。


import importlib, os, inspect


def get_modules_in_package(package_name: str):

    files = os.listdir(package_name)

    for file in files:

        if file not in ['__init__.py', '__pycache__']:

            if file[-3:] != '.py':

                continue


            file_name = file[:-3]

            module_name = package_name + '.' + file_name

            for name, cls in inspect.getmembers(importlib.import_module(module_name), inspect.isclass):

                if cls.__module__ == module_name:

                    yield cls


查看完整回答
反對 回復 2021-11-30
?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

這有點冗長,但您首先需要將文件作為模塊加載,然后檢查其方法以查看哪些是類:


import inspect

import importlib.util


# Load the module from file

spec = importlib.util.spec_from_file_location("foo", "foo.py")

foo = importlib.util.module_from_spec(spec)

spec.loader.exec_module(foo)


# Return a list of all attributes of foo which are classes

[x for x in dir(foo) if inspect.isclass(getattr(foo, x))]


查看完整回答
反對 回復 2021-11-30
  • 3 回答
  • 0 關注
  • 295 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號