LoginSignup
12
9

More than 5 years have passed since last update.

TypeError: 'str' object is not callable

Posted at

背景

動的型付言語初心者なもんで、これが出た時に最初よくわからなかったのでメモ。
テスト駆動開発を勉強がてらPythonで写経しているとき、第9章で"currency"の概念を導入するときに出会った。

変数名と関数名が同じになっている

class Money():
  def __init__(self, amount, currency):
    self.amount = amount
    self.amount = currency

  :

  def currency():
    return self.currency
  :

こうしてしまっていたため、関数の"currency"を呼び出しているかと思いきやと変数の"currency"という文字列に対してcallをしてしまっているらしい。
試しにインタプリタで以下を実行してみると、同じようなエラーが出る。

>>> 'USD'()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>

最初エラーの意味がよくわからなかったけど、よくよく考えれば当たり前のことだった…
とりあえずgetter/setter書いたり、変数の名前を"_currency"などに変えれば良いんだと思う。

12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9