【问题标题】:'function' object is not subscriptable in local package'function' 对象在本地包中不可下标
【发布时间】:2019-06-18 17:57:10
【问题描述】:

在尝试了解 Python 模块和包的工作原理时,我遇到以下错误,我找不到解决方法:

$ ./myMain.py
Traceback (most recent call last):
  File "./myMain.py", line 6, in <module>
    print(foobar.getKey['A'])
TypeError: 'function' object is not subscriptable

我的目录结构如下:

.
├── myMain.py*
└── utils/
    └── Foo/
        ├── __init__.py
        ├── __pycache__/
        │   ├── __init__.cpython-36.pyc
        │   └── foobar.cpython-36.pyc
        └── foobar.py

myMain.py 将是导入包的主要脚本。 myMain.py 代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from utils.Foo import foobar

print(foobar.getKey['A'])

__init__.py是一个空文件,foobar.py有函数定义:

TEST_DICT = {
        'A': 'This is A',
        'B': 'This is B'
}

def getKey(letter):
    return TEST_DICT[letter]

我在这里做错了什么?

【问题讨论】:

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


    【解决方案1】:

    在尝试从 Python 解释器中运行 myMain.py 中的代码后,我意识到函数调用是用错误的语法编写的。应该使用foobar.getKey('A') 而不是foobar.getKey['A'],因为我们调用的是函数而不是字典对象。

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2020-09-21
      • 2018-05-02
      • 2011-10-11
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多