[英]Python AttributeError: 'PostSaveCommand' object has no attribute '_server'
I'm building a python plugin, the code to do this is shown below: 我正在构建一个python插件,执行此操作的代码如下所示:
class BaseCommand(sublime_plugin.TextCommand):
@property
def server(self):
if self._server == None:
self._server = "My Server"
return self._server
class PostSaveCommand(BaseCommand):
def run(self, edit):
super().server.new_post("Title", "", "Text")
I alway getting the following error when I try to build the code: 当我尝试构建代码时,总是出现以下错误:
>>> view.run_command('post_save')
Traceback (most recent call last):
File "/Applications/Sublime Text.app/Contents/MacOS/sublime_plugin.py", line 1088, in run_
return self.run(edit)
File "/Users/joywek/Library/Application Support/Sublime Text 3/Packages/BlogPress/BlogPress.py", line 53, in run
super().server.new_post("Title", "", "Text")
File "/Users/joywek/Library/Application Support/Sublime Text 3/Packages/BlogPress/BlogPress.py", line 42, in server
if self._server == None:
AttributeError: 'PostSaveCommand' object has no attribute '_server'
We haven't defined what the attributes of sublime_plugin.TextCommand
are, but assuming that _server
is an attribute that you want to define as part of the BaseCommand
class, you need to instantiate that attribute in an __init__
method under the BaseCommand
class. 我们尚未定义sublime_plugin.TextCommand
的属性是什么,但是假设_server
是要定义为BaseCommand
类的一部分的属性,则需要在BaseCommand
类下的__init__
方法中实例化该属性。
For example: 例如:
class BaseCommand(sublime_plugin.TextCommand):
def __init__(self):
super().__init__()
self._server = None
@property
def server(self):
if self._server == None:
self._server = "My Server"
return self._server
class PostSaveCommand(BaseCommand):
def run(self, edit):
super().server.new_post("Title", "", "Text")
With that being said, you could get rid of the server()
method you've defined and simply instantiate _server
to be "My Server" as you desire, such as in the example below. 话虽如此,您可以摆脱定义的server()
方法,并_server
需要将_server
实例_server
“我的服务器”,例如下面的示例。
class BaseCommand(sublime_plugin.TextCommand):
def __init__(self):
super().__init__()
self._server = "My Server"
class PostSaveCommand(BaseCommand):
def __init__(self):
super().__init__()
def run(self, edit):
self._server.new_post("Title", "", "Text")
The problem is that BaseCommand
does not have _server
attribute set, when its server
property is accessed. 问题是, BaseCommand
没有_server
属性设置,当它的server
访问性能。 You are trying to check whether its None
: 您正在尝试检查其None
:
if self._server == None:
self._server = "My Server"
However, _server
attribute does not exist and this check raises the AttributeError
. 但是, _server
属性不存在,并且此检查引发AttributeError
。 You could instead check: 您可以改为检查:
if not hasattr(self, '_server') or self._server == None:
self._server = 'My Server'
Which would cover both cases: when attribute does not exist and when the value of _server
is equal to None
. 这将涵盖以下两种情况:属性不存在时和_server
的值等于None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.