1

このコードが機能しない理由がわかりません。

class convert_html(sublime_plugin.TextCommand):
  def convert_syntax(self, html, preprocessor)
    return "this is just a " + preprocessor + " test"

  def convert_to_jade(self, html):
    return self.convert_syntax(html, "jade")

  def run(self, edit):
    with open(self.view.file_name(), "r") as f:
      html = f.read()
      html = html.convert_to_jade(html)
      print(html)

それは言うAttributeError: 'str' object has no attribute 'convert_html'

どうすれば機能しますか?

4

1 に答える 1

6

クラスの現在のオブジェクトへの参照として機能する変数convert_to_jade()を使用してメソッドを呼び出す必要があります。またはのポインターにself非常に似ています。thisC++java

  html = self.convert_to_jade(html)

を呼び出すと、Python はこのインスタンス ハンドルをメソッドの最初の引数として暗黙的に渡しますself.something()。また、インスタンス ハンドル (つまりself) がないと、インスタンス変数にアクセスできません。

ところで、インスタンス メソッドの最初の引数に という名前を付けることは必須ではありませんselfが、一般的に使用される規則です。

詳しくはself こちら

次のコードが機能するはずです。

class convert_html(sublime_plugin.TextCommand):
  def convert_syntax(self, html, preprocessor):
    return "this is just a " + preprocessor + " test"

  def convert_to_jade(self, html):
    return self.convert_syntax(html, "jade")

  def run(self, edit):
    with open(self.view.file_name(), "r") as f:
      html = f.read()
      html = self.convert_to_jade(html)
      print(html)
于 2013-03-09T05:56:12.313 に答える