无法让 Python 从不同的文件夹导入 [英] Can't get Python to import from a different folder

查看:49
本文介绍了无法让 Python 从不同的文件夹导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法让 Python 在子文件夹中导入模块.当我尝试从导入的模块创建类的实例时出现错误,但导入本身成功.这是我的目录结构:

I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:

Server
    -server.py
    -Models
        --user.py

这里是 server.py 的内容:

Here's the contents of server.py:

from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user

u=user.User() #error on this line

还有 user.py:

And user.py:

class User(Entity):
    using_options(tablename='users')

    username = Field(String(15))
    password = Field(String(64))
    email    = Field(String(50))
    status   = Field(Integer)
    created  = Field(DateTime)

错误是:AttributeError: 'module' 对象没有属性 'User'

The error is: AttributeError: 'module' object has no attribute 'User'

推荐答案

我相信你需要在 Models 目录中创建一个名为 __init__.py 的文件,以便 python 将其视为一个模块.

I believe you need to create a file called __init__.py in the Models directory so that python treats it as a module.

然后你可以这样做:

from Models.user import User

您可以在 __init__.py 中包含代码(例如一些不同类需要的初始化代码)或将其留空.但它必须在那里.

You can include code in the __init__.py (for instance initialization code that a few different classes need) or leave it blank. But it must be there.

这篇关于无法让 Python 从不同的文件夹导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆