检查源代码中是否定义了python类

2024-04-23 15:03:20 发布

您现在位置:Python中文网/ 问答频道 /正文

如果定义了类,有没有一种简单的方法来检入python?即使您知道应该在其中定义类的模块文件.py的位置。你知道吗

假设我有这些文件,file1.py,我试图检查Class1是否在file2.py中定义。在file3.py中定义了第二个类Class2。你知道吗

在file1.py中,我有以下代码:

    try:
        modulePath = os.sep.join([cwd,os.sep.join(factory.split(".")[0:-1])]) + ".py"
        moduleName = factory.split(".")[-2]
        className = factory.split(".")[-1]
        m = imp.load_source(moduleName, modulePath)
        c = getattr(m, className)
    except:
        raise ValueError('Factory Path not correctly specified') 

在哪里

 factory = <string as path to the class 1> # for example com.Class1
 cwd = os.getcwd() # i.e. current working directory

在file2.py中

````

from . import Class2

Class1(object):
    def __init__(self):
        self.object2 = Class2()

在file3.py中

````

Class2(object):
    def __init__(self):
        pass

基本上,由于没有安装模块file2.py和file3.py,file1中的代码会产生一个错误,因为imp找不到Class2。我尝试了有没有相对的导入,没有成功。。。你知道吗


Tags: 模块文件代码pyself定义osfactory
1条回答
网友
1楼 · 发布于 2024-04-23 15:03:20

如果您知道类所在的位置,并且假设包含该类的模块位于python路径中,那么您可以将该类的导入包装在try块中

try:
    import MyClass
    #or
    from my_module import MyClass
except ImportError:
    #raise an exception or log a warning of some sort

相关问题 更多 >