我使用的是Python 2.7。我正在尝试运行我的UI自动化脚本,但是我得到了ImportError。
我至少有30个带方法的类。我希望在每个类中都有这些方法,这就是为什么我创建了BaseClass(MainClass)并创建了我所有类的对象。请告诉我在这种情况下应该怎么做,或者我如何解决这个问题。
这里的例子类似于我的代码。
test_class/baseclass.py
from test_class.first_class import FirstClass
from test_class.second_class import SecondClass
class MainClass:
def __init__(self):
self.firstclass = FirstClass()
self.secondclass = SecondClass()test_class/first_class.py
from test_class.baseclass import MainClass
class FirstClass(MainClass):
def __init__(self):
MainClass.__init__(self)
def add_two_number(self):
return 2 + 2test_class/second_class.py
from test_class.baseclass import MainClass
class SecondClass(MainClass):
def __init__(self):
MainClass.__init__(self)
def minus_number(self):
return self.firstclass.add_two_number() - 10
if __name__ == '__main__':
print(SecondClass().minus_number())当我运行最后一个文件时,我得到了这个错误
Traceback (most recent call last):
File "/Users/nik-edcast/git/ui-automation/test_class/second_class.py", line 1, in <module>
from test_class.baseclass import MainClass
File "/Users/nik-edcast/git/ui-automation/test_class/baseclass.py", line 1, in <module>
from test_class.first_class import FirstClass
File "/Users/nik-edcast/git/ui-automation/test_class/first_class.py", line 1, in <module>
from test_class.baseclass import MainClass
ImportError: cannot import name MainClass发布于 2018-05-14 00:39:48
检查这一行:从test_class.baseclass导入MainClass ->中,似乎所有其他导入的名称之间都有一个'_‘,比如second_class。因此,也许可以尝试编写base_class。谁知道会不会成功呢?
发布于 2018-05-14 01:09:22
你是否可以像python test_class/second_class.py一样运行你的代码。如果您只是这样做,那么python会认为查找模块的基目录是./test_class。因此,当您导入test_class包时,python将开始查找一个名为./test_class/test_class的文件夹来查找子模块。此目录不存在,因此导入失败。有几种方法可以告诉python如何正确地找到模块。
使用PYTHONPATH
解决这个问题的一种方法是在启动python之前设置PYTHONPATH。这只是一个环境变量,您可以使用它告诉python在哪里查找您的模块。
例如:
export PYTHONPATH=/path/to/your/root/folder
python test_class/second_class.py对python使用-m开关
默认情况下,python将主模块的目录视为查找其他模块的位置。然而,如果你使用的是-m,python将会退回到当前目录中查找。但您还需要指定要运行的模块的全名(而不是作为一个文件)。例如:
python -m test_class.second_class编写根入口点
在这里,我们只在基本级别(包含test_class的目录)定义主模块。Python将此文件夹视为查找用户模块的位置,并将适当地查找所有内容。例如:
main.py (在/path/to/your/root/folder中)
from test_class.second_class import SecondClass
if __name__ == '__main__':
print(SecondClass().minus_number())在命令行中
python main.py发布于 2018-05-14 13:05:43
您可以尝试导入完整文件,而不是使用from file import类。然后,在引用其他文件中的内容之前,只需添加文件名即可。
https://stackoverflow.com/questions/50318309
复制相似问题