Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我的Python代码还有改进的余地吗?_Python_Pygtk_Gedit - Fatal编程技术网

我的Python代码还有改进的余地吗?

我的Python代码还有改进的余地吗?,python,pygtk,gedit,Python,Pygtk,Gedit,我正在使用Python(和PyGTK)开发一个Gedit插件,但我还没有太多地使用Python,所以我不知道我是否在编写Python代码 我自己的所有代码都包含在中。还有一些其他文件,但它们来自我正在连接的外部图书馆。我的\uuuu init\uuuu.py如下所示: # # @file __init__.py # Does the heavy lifting behind connecting Zen Coding to Gedit. # import gedit, gobject, str

我正在使用Python(和PyGTK)开发一个Gedit插件,但我还没有太多地使用Python,所以我不知道我是否在编写Python代码

我自己的所有代码都包含在
中。还有一些其他文件,但它们来自我正在连接的外部图书馆。我的
\uuuu init\uuuu.py
如下所示:

#
# @file __init__.py
# Does the heavy lifting behind connecting Zen Coding to Gedit.
#

import gedit, gobject, string, gtk, re, zen_core

class ZenCodingPlugin(gedit.Plugin):
    """
    A Gedit plugin to implement Zen Coding's HTML and CSS shorthand expander.

    This file adds the menu items and keyboard shortcuts to the UI and connects
    those items with the good stuff (i.e., the code expansion).
    """

    def __init__(self):
        gedit.Plugin.__init__(self)

    def activate(self, window):
        "Gedit callback: install the expansion feature into the UI"

        ui_manager = window.get_ui_manager()
        action_group = gtk.ActionGroup("GeditZenCodingPluginActions")

        # Create the GTK action to be used to connect the key combo
        # to the Zen Coding expansion (i.e., the good stuff).
        complete_action = gtk.Action(name="ZenCodingAction",
                                     label="Expand Zen code...",
                                     tooltip="Expand Zen Code in document to raw HTML",
                                     stock_id=gtk.STOCK_GO_FORWARD)

        # Connect the newly created action with key combo
        complete_action.connect("activate",
                                lambda a: self.expand_zencode(window))
        action_group.add_action_with_accel(complete_action,
                                           "<Ctrl><Shift>E")

        ui_manager.insert_action_group(action_group, 0)

        # @TODO: Figure out what these lines do
        ui_merge_id = ui_manager.new_merge_id()
        ui_manager.add_ui(ui_merge_id,
                          "/MenuBar/EditMenu/EditOps_5",
                          "ZenCoding",
                          "ZenCodingAction",
                          gtk.UI_MANAGER_MENUITEM, False)
        ui_manager.__ui_data__ = (action_group, ui_merge_id)

    def deactivate(self, window):
        "Gedit callback: get rid of the expansion feature"

        ui_manager = window.get_ui_manager()
        (action_group, ui_merge_id) = ui_manager.__ui_data__

        # Remove the UI data, action group, and UI itself from Gedit
        del ui_manager.__ui_data__
        ui_manager.remove_action_group(action_group)
        ui_manager.remove_ui(ui_merge_id)


    def expand_zencode(self, window):
        "The action which handles the code expansion itself."

        view = window.get_active_view()
        buffer = view.get_buffer()

        # Grab the current cursor position.
        cursor_iter = buffer.get_iter_at_mark(buffer.get_insert())

        # Grab the first character in the line.
        line_iter = cursor_iter.copy()
        line_iter.set_line_offset(0)

        # Grab the text from the start of the line to the cursor.
        line = buffer.get_text(line_iter, cursor_iter)

        # Find the last space in the line and remove it, setting a variable
        # 'before' to the current line.
        words = line.split(" ")
        before = words[-1].lstrip()
        if not before:
            return

        # Get the language of the current document. Second line prevents an error
        # if first line returns None.
        lang = window.get_active_document().get_language()
        lang = lang and lang.get_name()

        # Using the 'before' variable, convert it from Zen Code
        # to expanded code. If there isn't anything, just return.
        if lang == 'CSS':
            after = zen_core.expand_abbreviation(before,'css','xhtml')
        else:
            after = zen_core.expand_abbreviation(before,'html','xhtml')
        if not after:
            return

        # Grab the line's indentation and store it.
        indent = re.match(r"\s*", line).group()

        # Automatically indent the string and replace \t (tab) with the
        # correct number of spaces.
        after = zen_core.pad_string(after,indent)
        if view.get_insert_spaces_instead_of_tabs():
            tabsize = view.get_tab_width()
            spaces = " " * tabsize
            after = after.replace("\t",spaces)

        # We are currently lame and do not know how to do placeholders.
        # So remove all | characters from after.
        after = after.replace("|", "")

        # Delete the last word in the line (i.e., the 'before' text, aka the
        # Zen un-expanded code), so that we can replace it.
        word_iter = cursor_iter.copy()
        position_in_line = cursor_iter.get_line_index() - len(before)
        word_iter.set_line_index(position_in_line)
        buffer.delete(word_iter, cursor_iter)

        # Insert the new expanded text.
        buffer.insert_at_cursor(after)
#
#@file\uuuu init\uuuuu.py
#在将Zen编码连接到Gedit之后完成繁重的工作。
#
导入gedit、gobject、string、gtk、re、zen_核心
类ZenCodingPlugin(gedit.Plugin):
"""
一个Gedit插件,用于实现Zen编码的HTML和CSS速记扩展器。
此文件将菜单项和键盘快捷键添加到UI并连接
那些有好东西的项目(即代码扩展)。
"""
定义初始化(自):
插件。初始化(self)
def激活(自我,窗口):
“Gedit回调:将扩展功能安装到UI中”
ui\u manager=window.get\u ui\u manager()
action_group=gtk.ActionGroup(“GeditZenCodingPluginActions”)
#创建用于连接按键组合的GTK操作
#到禅宗编码扩展(即,好东西)。
完成_action=gtk.action(name=“ZenCodingAction”,
label=“扩展禅码…”,
tooltip=“将文档中的禅码扩展为原始HTML”,
股票id=gtk.股票前进)
#用组合键连接新创建的操作
完成操作。连接(“激活”,
lambda:self.expand_zencode(窗口))
动作组。添加动作和加速(完成动作,
“E”)
ui\u管理器。插入\u操作\u组(操作\u组,0)
#@TODO:弄清楚这些线是干什么的
ui\u merge\u id=ui\u manager.new\u merge\u id()
用户界面管理器。添加用户界面(用户界面合并id,
“/MenuBar/EditMenu/EditOps_5”,
“天顶编码”,
“ZenCodingAction”,
gtk.UI_MANAGER_MENUITEM,False)
用户界面管理器。用户界面数据(操作组,用户界面合并id)
def停用(自我,窗口):
“Gedit回调:删除扩展功能”
ui\u manager=window.get\u ui\u manager()
(操作组,用户界面合并id)=用户界面管理器__
#从Gedit中删除UI数据、操作组和UI本身
删除用户界面管理器__
ui\u管理器。删除\u操作组(操作组)
ui\u管理器。删除\u ui(ui\u合并\u id)
def expand_zencode(自身,窗口):
“处理代码扩展本身的操作。”
视图=窗口。获取活动视图()
buffer=view.get_buffer()
#抓取当前光标位置。
游标\u iter=buffer.get\u iter\u在\u标记处(buffer.get\u insert())
#抓取行中的第一个字符。
行\u iter=光标\u iter.copy()
测线仪。设置测线偏移(0)
#从行首到光标抓取文本。
line=buffer.get\u text(line\u iter,cursor\u iter)
#找到行中的最后一个空格并删除它,设置一个变量
#“before”到当前行。
单词=行。拆分(“”)
before=单词[-1].lstrip()
如果不是在之前:
返回
#获取当前文档的语言。第二行防止出错
#如果第一行返回None。
lang=window.get\u active\u document().get\u language()
lang=lang和lang.get_name()
#使用“before”变量,将其从Zen代码转换为
#扩展代码。如果没有什么,就回来。
如果lang=='CSS':
after=zen\u core.expand\u缩写(在“css”和“xhtml”之前)
其他:
after=zen\u core.expand\u缩写(在'html'和'xhtml'之前)
如果不是在之后:
返回
#抓取线条的缩进并保存它。
缩进=重新匹配(r“\s*”,第行).group()
#自动缩进字符串并将\t(制表符)替换为
#正确的空格数。
after=zen\u core.pad\u字符串(after,缩进)
如果查看。获取\u插入\u空格\u而不是\u选项卡():
tabsize=view.get\u tab\u width()
空格=“”*tabsize
after=after.replace(“\t”,空格)
#我们目前是跛脚的,不知道如何做占位符。
#因此,从后面删除所有|字符。
after=after.replace(“|”,”)
#删除行中的最后一个单词(即“before”文本,又名
#Zen(未扩展代码),以便我们可以替换它。
word\u iter=cursor\u iter.copy()
定位线=光标。获取线索引()-len(之前)
文字索引。设置行索引(行中的位置)
buffer.delete(字、光标)
#插入新的展开文本。
缓冲区。在\u光标处插入\u(之后)
我这么问是因为上面的内容似乎不是很面向对象的,我觉得在
\uuu init\uuuuuuuuy.py
中加入这么多逻辑是个坏主意,但作为一个新手,我不确定

还有改进的余地吗?如果是,怎么做


(我试图回避插件的实际功能,因为我更多的是寻找一个编码风格的评审,而不是对数评审,但是如果您需要查看外部库中的代码,整个插件位于)

也许您想将其移动到一个名为
zen\u plugin.py

from zen_plugin import ZenCodingPlugin
然后使您的
\uuuu init\uuuuuuuuuuuy.py

from zen_plugin import ZenCodingPlugin

我从来没有做过GEdit插件,所以我不能对_init__u;.py问题发表评论,但一般注意:

  • 在没有新参数的情况下调用parent的_uinit _;不是多余的吗?你不能去掉这两行吗

  • 您创建的局部变量比我创建的多。我不得不四处寻找,看看一个值是从哪里来的,或者它是否被再次使用。例如:

    tabsize = view.get_tab_width()
    spaces = " " * tabsize
    after = after.replace("\t",spaces)
    
    可以是:

    after = after.replace("\t", " " * view.get_tab_width())
    
  • after = zen_core.expand_abbreviation(before, 'css' if lang == 'CSS' else 'html', 'xhtml')
    
    def __init__(self):
        gedit.Plugin.__init__(self)
    
    pluginname
    `- __init__.py
    
    pluginname.py
    
    pluginname
    +- __init__.py
    `- plugin.py
    
    from pluginname.plugin import ZenCodingPlugin