Skip to main content
 首页 » 编程设计

python之定义不起作用

2025年05月04日19yyy_WW

不确定为什么这段代码不起作用。

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++或java

中的 this指针
  html = self.convert_to_jade(html) 

当您调用 self.something() 时,Python 将此实例句柄作为第一个参数隐式传递给该方法。如果没有实例句柄(即 self),您将无法访问任何实例变量。

顺便说一句,将实例方法的第一个参数命名为 self 不是强制性的,但这是一个常用的约定。

关于 self 的更多信息 here

下面的代码应该可以工作:

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)