Python inheritance/polymorphism

Python inheritance/polymorphism

我正在玩这个 Python 图书馆:

Read The Docs

PopUpDialog

有一个名为 PopUpDialog 的 object,其基础 class 属于 Frame 类型。

Frame object 的 fields 之一是 can_scroll=True .

当我实例化 字段时,我希望这个字段False =]PopUpDialog,所以没有滚动条

我试着做了一个新的class

class PopUpDialogNoScroll(PopUpDialog):
    super(PopUpdDialogNoScroll, self).__init__(screen,...

class PopUpDialogNoScroll(Frame):
    super(PopUpdDialogNoScroll, self).__init__(screen,...

但是,我所有的尝试都导致了错误,例如 "7 个参数给出 2 个是预期的"

有人能告诉我如何 导出 class 并设置 parent 的字段and/or 盛大parent class?

谢谢,愿你安好

编辑 感谢 awarrier 99 我走到这一步,但是滚动条仍然可见。这里我有一些演示代码。

from asciimatics.widgets import Frame, ListBox, Layout, Divider, Text, TextBox, Widget, Button, Label, DropdownList, PopUpDialog, CheckBox, RadioButtons, PopupMenu
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError, NextScene, StopApplication, InvalidFields


class PopUpDialogNoScroll(PopUpDialog):
    def __init__(self, *args, **kwargs):
        super(PopUpDialogNoScroll, self).__init__(*args, **kwargs)
        self.can_scroll = False
        self.has_border = False


class DemoView(Frame):
    def __init__(self, screen):
        super(DemoView, self).__init__(screen,
                                          11,
                                          48,
                                          data=None,
                                          on_load=None,
                                          has_border=True,
                                          hover_focus=True,
                                          name=None,
                                          title="Welcome",
                                          x=None,
                                          y=None,
                                          has_shadow=False,
                                          reduce_cpu=False,
                                          is_modal=False,
                                          can_scroll=False)


        body = Layout([1], fill_frame=True)
        self.add_layout(body)
        button = Button("Click me", self.clicked, label=None)
        body.add_widget(button, 0)


    def clicked(self):
      self._scene.add_effect(
          PopUpDialogNoScroll(self.screen, "1..\n2..\n3..\n4..\n5..  ", ["OK"], on_close=self.done, has_shadow=False, theme='info'))

    def done(self):
        pass


last_scene = None

def demo(screen, scene):
  scenes = [
    Scene([DemoView(screen)], duration=-1, clear=True, name="demo"),
  ]

  screen.play(scenes, stop_on_resize=False, unhandled_input=None, start_scene=scene, repeat=True, allow_int=True)

Screen.wrapper(demo, catch_interrupt=True, arguments=[last_scene])

首先,任何对 super 的调用都应该在 class 自己的 __init__ 函数的第一行中进行。所以你的 class 应该有自己的 __init__ 函数。然后,要将您想要的所有参数传递给原始 class,您可以提供两个参数来合并继承的 class 将具有的所有参数:*args**kwargs.然后,您可以在 __init__ 函数中将 can_scroll 字段显式设置为 False,如下所示:

class PopUpDialogNoScroll(PopUpDialog):
    def __init__(self, *args, **kwargs):
        super(PopUpDialogNoScroll, self).__init__(*args, **kwargs)
        self.can_scroll = False

通过 *args**kwargs,您可以传入原始 PopUpDialog class 期望的任何参数,而无需显式重写它们,您可以提供他们到 super class

编辑: 当您将代码迁移到 Python 3 时,您可以将 super 调用更改为以下 Python 3 中的新语法:super().__init(*args, **kwargs)。请注意,唯一的区别是您不必明确指定 class 名称和 self 引用


编辑 2: 查看提供的源代码 here,我可以通过复制他们用于 PopUpDialog class 的任何代码,然后更改来制作 PopUpDialogNoScroll class这行来自他们的来源:

super(PopUpDialog, self).__init__(screen, height, width, self._data, has_shadow=has_shadow, is_modal=True)

至:

super(PopUpDialogNoScroll, self).__init__(screen, height, width, self._data, has_shadow=has_shadow, is_modal=True, can_scroll=False)

不是最优雅的解决方案,但它有效

from asciimatics.widgets import Frame, ListBox, Layout, Divider, Text, TextBox, Widget, Button, Label, DropdownList, PopUpDialog, CheckBox, RadioButtons, PopupMenu
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError, NextScene, StopApplication, InvalidFields
from wcwidth import wcswidth
from functools import partial

def _enforce_width(text, width, unicode_aware=True):
    """
    Enforce a displayed piece of text to be a certain number of cells wide.  This takes into
    account double-width characters used in CJK languages.
    :param text: The text to be truncated
    :param width: The screen cell width to enforce
    :return: The resulting truncated text
    """
    # Double-width strings cannot be more than twice the string length, so no need to try
    # expensive truncation if this upper bound isn't an issue.
    if (2 * len(text) < width) or (len(text) < width and not unicode_aware):
        return text

    # Can still optimize performance if we are not handling unicode characters.
    if unicode_aware:
        size = 0
        for i, c in enumerate(str(text)):
            w = wcwidth(c) if ord(c) >= 256 else 1
            if size + w > width:
                return text[0:i]
            size += w
    elif len(text) + 1 > width:
        return text[0:width]
    return text

def _split_text(text, width, height, unicode_aware=True):
    """
    Split text to required dimensions.
    This will first try to split the text into multiple lines, then put a "..." on the last
    3 characters of the last line if this still doesn't fit.
    :param text: The text to split.
    :param width: The maximum width for any line.
    :param height: The maximum height for the resulting text.
    :return: A list of strings of the broken up text.
    """
    # At a high level, just try to split on whitespace for the best results.
    tokens = text.split(" ")
    result = []
    current_line = ""
    string_len = wcswidth if unicode_aware else len
    for token in tokens:
        for i, line_token in enumerate(token.split("\n")):
            if string_len(current_line + line_token) > width or i > 0:
                # Don't bother inserting completely blank lines - which should only happen on the very first
                # line (as the rest will inject whitespace/newlines)
                if len(current_line) > 0:
                    result.append(current_line.rstrip())
                current_line = line_token + " "
            else:
                current_line += line_token + " "

    # At this point we've either split nicely or have a hugely long unbroken string (e.g. because the
    # language doesn't use whitespace.  Either way, break this last line up as best we can.
    current_line = current_line.rstrip()
    while string_len(current_line) > 0:
        new_line = _enforce_width(current_line, width, unicode_aware)
        result.append(new_line)
        current_line = current_line[len(new_line):]

    # Check for a height overrun and truncate.
    if len(result) > height:
        result = result[:height]
        result[height - 1] = result[height - 1][:width - 3] + "..."

    # Very small columns could be shorter than individual words - truncate
    # each line if necessary.
    for i, line in enumerate(result):
        if len(line) > width:
            result[i] = line[:width - 3] + "..."
    return result

class PopUpDialogNoScroll(Frame):
    """
    A fixed implementation Frame that provides a standard message box dialog.
    """

    def __init__(self, screen, text, buttons, on_close=None, has_shadow=False, theme="warning"):
        """
        :param screen: The Screen that owns this dialog.
        :param text: The message text to display.
        :param buttons: A list of button names to display. This may be an empty list.
        :param on_close: Optional function to invoke on exit.
        :param has_shadow: optional flag to specify if dialog should have a shadow when drawn.
        :param theme: optional colour theme for this pop-up.  Defaults to the warning colours.
        The `on_close` method (if specified) will be called with one integer parameter that
        corresponds to the index of the button passed in the array of available `buttons`.
        Note that `on_close` must be a static method to work across screen resizing.  Either it
        is static (and so the dialog will be cloned) or it is not (and the dialog will disappear
        when the screen is resized).
        """
        # Remember parameters for cloning.
        self._text = text
        self._buttons = buttons
        self._on_close = on_close

        # Decide on optimum width of the dialog.  Limit to 2/3 the screen width.
        string_len = wcswidth if screen.unicode_aware else len
        width = max([string_len(x) for x in text.split("\n")])
        width = max(width + 2,
                    sum([string_len(x) + 4 for x in buttons]) + len(buttons) + 5)
        width = min(width, screen.width * 2 // 3)

        # Figure out the necessary message and allow for buttons and borders
        # when deciding on height.
        dh = 4 if len(buttons) > 0 else 2
        self._message = _split_text(text, width - 2, screen.height - dh, screen.unicode_aware)
        height = len(self._message) + dh

        # Construct the Frame
        self._data = {"message": self._message}
        super(PopUpDialogNoScroll, self).__init__(
            screen, height, width, self._data, has_shadow=has_shadow, is_modal=True, can_scroll=False)

        # Build up the message box
        layout = Layout([width - 2], fill_frame=True)
        self.add_layout(layout)
        text_box = TextBox(len(self._message), name="message")
        text_box.disabled = True
        layout.add_widget(text_box)
        layout2 = Layout([1 for _ in buttons])
        self.add_layout(layout2)
        for i, button in enumerate(buttons):
            func = partial(self._destroy, i)
            layout2.add_widget(Button(button, func), i)
        self.fix()

        # Ensure that we have the right palette in place
        self.set_theme(theme)

    def _destroy(self, selected):
        self._scene.remove_effect(self)
        if self._on_close:
            self._on_close(selected)

    def clone(self, screen, scene):
        """
        Create a clone of this Dialog into a new Screen.
        :param screen: The new Screen object to clone into.
        :param scene: The new Scene object to clone into.
        """
        # Only clone the object if the function is safe to do so.
        if self._on_close is None or isfunction(self._on_close):
            scene.add_effect(PopUpDialog(screen, self._text, self._buttons, self._on_close))

class DemoView(Frame):
    def __init__(self, screen):
        super(DemoView, self).__init__(screen,
                                          11,
                                          48,
                                          data=None,
                                          on_load=None,
                                          has_border=True,
                                          hover_focus=True,
                                          name=None,
                                          title="Welcome",
                                          x=None,
                                          y=None,
                                          has_shadow=False,
                                          reduce_cpu=False,
                                          is_modal=False,
                                          can_scroll=False)


        body = Layout([1], fill_frame=True)
        self.add_layout(body)
        button = Button("Click me", self.clicked, label=None)
        body.add_widget(button, 0)


    def clicked(self):
      self._scene.add_effect(
          PopUpDialogNoScroll(self.screen, "1..\n2..\n3..\n4..\n5..  ", ["OK"], on_close=self.done, has_shadow=False, theme='info'))

    def done(self):
        pass


last_scene = None

def demo(screen, scene):
  scenes = [
    Scene([DemoView(screen)], duration=-1, clear=True, name="demo"),
  ]

  screen.play(scenes, stop_on_resize=False, unhandled_input=None, start_scene=scene, repeat=True, allow_int=True)

Screen.wrapper(demo, catch_interrupt=True, arguments=[last_scene])