【问题标题】:Python: AttributeError module x has no attribute yPython:AttributeError 模块 x 没有属性 y
【发布时间】:2018-05-28 08:07:12
【问题描述】:

我有一个目录结构如下的项目

.
├── Pipfile
├── Pipfile.lock
├── module
│   ├── __init__.py
│   ├── helpers
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   └── __init__.cpython-36.pyc
│   │   ├── dynamo.py
│   │   └── logger.py
│   └── test.py

相关代码

logger.py

import click
import sys
from tabulate import tabulate


def formatter(string, *rest):
    return string.format(*rest)


def info(*rest):
    """Write text in blue color
    """
    click.echo(click.style('☵ ' + formatter(*rest), fg='blue'))

test.py

import helpers

helpers.logger.info('Trying')

当我尝试使用命令运行时

python3 module/test.py

我收到此错误

Traceback (most recent call last):
  File "module/test.py", line 4, in <module>
    helpers.logger.info('Trying')
AttributeError: module 'helpers' has no attribute 'logger'

我尝试过重构代码。将helpers 目录放在外面,与module 目录平齐。但它仍然没有工作,它不应该有,从我读到的。我尝试对__init__.py 和python 模块系统进行一些研究。我读得越多,它就越混乱。但无论我学到什么,我都创建了另一个示例项目。采用如下结构,

.
└── test
    ├── __init__.py
    ├── helpers
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── __init__.cpython-36.pyc
    │   │   └── quote.cpython-36.pyc
    │   └── quote.py
    ├── index.py
    ├── logger
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── __init__.cpython-36.pyc
    │   │   └── info.cpython-36.pyc
    │   └── info.py

代码与第一个项目相同。

当我这样做的时候,

python3 test/index.py

它按预期工作。两个项目的唯一区别:

在第一个项目中,我使用pipenv来安装deps并创建虚拟环境。

【问题讨论】:

  • 这不是 Python 包导入的工作方式。如果要使用logger,需要显式导入;最好的方法是使用from helpers import logger,然后使用logger.info(...)。但是,您也应该考虑不这样做,而是使用 stdlib 中的 logging 模块。

标签: python python-3.x module python-module pipenv


【解决方案1】:

使用您的初始布局(将loggers 作为helpers 包的子模块),您需要在helpers/__init__.py 中显式导入loggers 以将其公开为helpers 包的属性:

# helpers/__init__.py
from . import logger

【讨论】:

  • 经过无数次 stackoverflow 搜索,这就是我一直在寻找的答案 - 谢谢!
  • 作为 python 新手,这非常有帮助
【解决方案2】:

logger 是模块而不是属性,helpers.loggerlogger 评估为属性。其实你应该这样做:

from helpers import logger

print(logger.info('Trying'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 2016-06-26
    • 2016-11-08
    • 2014-04-26
    • 2021-01-15
    • 2020-03-09
    • 2013-05-14
    相关资源
    最近更新 更多