python3导入类,Python 3从子文件夹导入类问题

I have a strange problem regarding import classes from subfolders.

I'm using Python 3.6, therefore an __init__.py should be not required in the subfolders.

I have the following file structure:

root

├── script.py (main)

└── custom

├── class1.py

└── class2.py

This is script.py:

from custom.class1 import Class1

from custom.class2 import Class2

if __name__ == '__main__':

cl1 = Class1()

cl2 = Class2()

This is class1.py:

class Class1():

def __init__(self):

print('Class1')

if __name__ == '__main__':

cl1 = Class1()

This is class2.py, which imports also class1:

from class1 import Class1

class Class2():

def __init__(self):

cl1 = Class1()

print('Class2')

if __name__ == '__main__':

cl2 = Class2()

And now the problem:

It works without error, when i am running python class1.py in the custom subfolder.

It works without error, when i am running python class2.py in the custom subfolder.

But when i am running python script.py in the root folder, i get the following error:

Traceback (most recent call last):

File .... in

from custom.class2 import Class2

File .... line 1, in

from class1 import Class1

ModuleNotFoundError: No module named 'class1'

How can this be fixed in a way, that the scripts in the custom subfolders can be run on its own and also the script in the root folder works?

解决方案

The problem is that you are running custom.class2 inside of script.py, which means while running custom.class2, you are still in the root directory.

To fix this, you should replace from class1 import Class1 from class2.py with from custom.class1 import Class1.

If you need to be able to run the file from any working directory, you may replace it's contents with this:

import os

import sys

path = os.path.abspath(os.path.dirname(__file__))

if not path in sys.path:

sys.path.append(path)

from class1 import Class1

class Class2():

def __init__(self):

cl1 = Class1()

print('Class2')

if __name__ == '__main__':

cl2 = Class2()

The code adds the file's path in to the sys.path list, which holds different paths from which you can import modules.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值