1. ホーム
  2. python

[解決済み】 TypeError: 'builtin_function_or_method' オブジェクトに '__getitem__' 属性がない。

2022-01-21 11:39:11

質問

簡単な 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 はメソッドであり () ではなく [] . カスラさんの例で言うと

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