繁体   English   中英

TypeError:'builtin_function_or_method'对象没有属性'__getitem__'

[英]TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

我有简单的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脚本以便在文件系统中的任何位置运行它?(我想通过提供模板的路径在当前文件夹的文件系统中的任何位置生成文件)

问题是index是一个方法,需要用()而不是[]来调用。 要使用Kasra的例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM