0

Not sure why this code doesn't work.

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)

It says AttributeError: 'str' object has no attribute 'convert_html'

How do I make it work?

Jasper
  • 5,090
  • 11
  • 34
  • 41

1 Answers1

6

You need to invoke the convert_to_jade() method using the the self variable, which acts as a reference to the current object of the class. Quite similar to the this pointer in C++ or java

  html = self.convert_to_jade(html)

Python passes this instance handle implicitly as the first argument to the method when you invoke self.something(). And without the instance handle (i.e. self), you would not be able to access any instance variables.

BTW, it is not mandatory to name the first argument of instance methods as self, but it is a commonly used convention.

More on self here

The following code should work:

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)
Community
  • 1
  • 1
Tuxdude
  • 47,485
  • 15
  • 109
  • 110
  • I've also tried `html = convert_to_jade(html)` and `def convert_to_jade(html):` but it didn't work. Can you explain please, why? – Jasper Mar 09 '13 at 06:02
  • @Steve - have updated the answer with more info about why you need to use `self` and also a link to another SO question, which should give you all the details about `self`. – Tuxdude Mar 09 '13 at 06:18