【问题标题】:TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'TypeError:“builtin_function_or_method”对象没有属性“__getitem__”
【发布时间】:2018-04-20 03:46:32
【问题描述】:

我有简单的python 函数。

def readMainTemplate(templateFile):
    template = open(templateFile, 'r')
    data = template.read()
    index1 = data.index['['] #originally I passed it into data[]
    index2 = data.index[']']
    template.close()
    return data[index1:index2]

def writeMainTemplate(template, name):
    file = open(name, 'w')
    file.write(template)
    file.close()

#runMainTemplate('main.template')
def runMainTemplate(template):
    code = readMainTemplate(template)
    writeMainTemplate(code, 'main.cpp')

他们基本上假设从文件中读取某种模板(类似这样)

--template "main"
[
        #include <iostream>

        using namespace std;

        int main()
        {
            return 0;
        }
]

然后写入文件(基本生成main.cpp模板)

我使用这个命令从命令行运行它

python -c "from genmain import runMainTemplate; runMainTemplate('main.template')"

但是我遇到了这个错误

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "genmain.py", line 18, in runMainTemplate
    code = readMainTemplate(template)
  File "genmain.py", line 6, in readMainTemplate
    index1 = data.index['['] #originally I passed it into data[]
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

我认为data = template.read() 应该返回string 并且字符串应该允许执行操作切片[:]

但为什么会出现错误?

还有一个问题我应该把python 脚本放在哪里以便在文件系统中的任何位置运行它?(我想通过提供在当前文件夹的文件系统中的任何位置生成文件模板路径)

【问题讨论】:

    标签: python


    【解决方案1】:

    问题是index是一个方法,需要用()而不是[]调用。以 Kasra 为例:

    >>> s="aeer"
    >>> s.index('a')
    0
    

    【讨论】:

    • 哦,非常愚蠢的错误,我想念()! :)
    猜你喜欢
    • 2012-10-16
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2012-10-15
    • 2014-01-16
    • 2017-02-27
    • 2018-01-28
    相关资源
    最近更新 更多