Python 类型错误:'builtin_function_or_method' 对象没有属性 '__getitem__'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27702727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
提问by lapots
I've got simple python
functions.
我有简单的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')
They basically suppose to read from file some kind of template(something like this)
他们基本上假设从文件中读取某种模板(像这样)
--template "main"
[
#include <iostream>
using namespace std;
int main()
{
return 0;
}
]
and then write it to file(basically generating main.cpp
template)
然后将其写入文件(基本上生成main.cpp
模板)
I run it from command line using this command
我使用此命令从命令行运行它
python -c "from genmain import runMainTemplate; runMainTemplate('main.template')"
but I've got this error
但我有这个错误
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__'
I thought that data = template.read()
supposed to return string
and string should allow to perform operation slicing [:]
.
我认为data = template.read()
应该返回string
并且字符串应该允许执行操作切片[:]
。
But why there is an error?
但是为什么会出现错误呢?
Also a question: where I should put python
scripts in order to run it anywhere in filesystem?(I want to generate file anywhere in the filesystem in the current folder by providing path to the template)
还有一个问题:我应该把python
脚本放在哪里才能在文件系统的任何地方运行它?(我想通过提供模板路径在当前文件夹的文件系统中的任何地方生成文件)
采纳答案by Daniel Roseman
The problem is that index
is a method and needs to be called with ()
not []
. To use Kasra's example:
问题是这index
是一个方法,需要用()
not调用[]
。使用 Kasra 的例子:
>>> s="aeer"
>>> s.index('a')
0