1

我是一名业余程序员,自学 Python。由于 curses 模块在 Windows 上不起作用,我一直在研究 UniCurses,一个跨平台的 Curses 实现。我很失望地发现 UniCurses 函数与我喜欢的 Python 风格几乎没有相似之处,这可能是由于遗留支持和历史原因。例如,要将文本添加到终端内的“窗口”,您可以调用waddstr(WINDOW, str, [attr])mvwaddstr(WINDOW, y, x, str, [attr])。有许多这些隐秘命名的函数需要将窗口作为参数传递,并且不要将窗口视为具有方法、实例变量等的对象。

我更喜欢以 Pythonic 风格编写,其中在窗口和面板对象上调用方法,例如window_instance.add_string(string, [attr]),理想情况下为方法提供可选的 x 和 y 参数以合并mvwaddstr()到与waddstr().

想到实现这一点的方法是为窗口构造定义一个类,如下所示:

import unicurses 
# this would normally be 'from unicurses import * ' but I'm trying to being explicit here

...

class PseudoWindow(object):
    def __init__(self, num_cols,num_lines, begin_x, begin_y):
        self.id = unicurses.newwin(nlines, ncols, begin_y, begin_x) 
        # use this value in unicurses functions

    def __del__(self):
        unicurses.delwin(self.id)

    def add_string(self, string, [attr], x = None, y = None)
        if x is None and y is None:
            unicurses.waddstr(self.id, string, [attr])
        else:
            unicurses.mvwaddstr(self.id, string, y, x, [attr])

    # wrap further unicurses functions into methods of PseudoWindow as required

作为一个没有经验的程序员,从一种语言切换到另一种语言的心理成本有点高,用更熟悉的语法包装这些函数似乎对提高生活质量有很大好处。我是否遗漏了有关如何使用 UniCurses 的内容?以这种方式将 API 包装在更深一层的抽象层中有什么缺点和陷阱?这种方法是否有替代方法仍然允许我使用标准的面向对象的 Python 语法?

4

0 回答 0