不知道为什么这段代码不起作用.
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)
Run Code Online (Sandbox Code Playgroud)
它说 AttributeError: 'str' object has no attribute 'convert_html'
我如何使其工作?
您需要convert_to_jade()使用self变量调用该方法,该变量充当对类的当前对象的引用.非常类似于或中的this指针C++java
html = self.convert_to_jade(html)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)