この記事は3年以上前に書かれた記事で内容が古い可能性があります
とある日に、「TypeError: ‘str’ object is not callable」というエラーにハマった(Python)
2021-01-21
とある日に、「TypeError: ‘str’ object is not callable」というエラーにハマったのでメモ
以下のようなコードを実行すると
% cat typeerror_test.py
#!/usr/bin/env python
# coding: utf-8
# import sys
class TestClass():
# constractor
def __init__(self,hogehoge):
self.hogehoge = hogehoge
def hogehoge(self):
return self.hogehoge
# Execution
if __name__ == "__main__":
test = TestClass("hogehoge")
print(test.hogehoge())
こんなエラーが出る
% python typeerror_test.py
Traceback (most recent call last):
File "typeerror_test.py", line 18, in <module>
print(test.hogehoge())
TypeError: 'str' object is not callable
問題は、インスタンス変数とメソッド名が同じことで起こるとのこと
参考:TypeError: ‘str’ object is not callable
クラス内の変数は「hogehoge」
self.hogehoge = hogehoge
クラス内のメソッドも「hogehoge」
def hogehoge(self):
解決法としては、インスタンス変数か、メソッド名を変更すること
今回は、インスタンス変数の頭に「_hogehoge」と、アンダースコアをつけることで解決
(こういう問題があるからなのか、慣習的にインスタンス変数にはアンダースコアをつけるらしい)
変更後のコード
% cat typeerror_test.py
#!/usr/bin/env python
# coding: utf-8
# import sys
class TestClass():
# constractor
def __init__(self,hogehoge):
self._hogehoge = hogehoge
def hogehoge(self):
return self._hogehoge
# Execution
if __name__ == "__main__":
test = TestClass("hogehoge")
print(test.hogehoge())
実行結果
% python typeerror_test.py hogehoge
以上。