簡體   English   中英

防衛不起作用

[英]Def 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)

它說AttributeError: 'str' object has no attribute 'convert_html'

我該如何運作?

您需要使用self變量來調用convert_to_jade()方法,該變量用作對該類當前對象的引用。 非常類似於C++javathis指針

  html = self.convert_to_jade(html)

當您調用self.something()時,Python會隱式將此實例句柄作為方法的第一個參數傳遞。 而且如果沒有實例句柄(即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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM