此 Python 代码中多重继承的最佳实践

mad*_*tyn 2 tkinter multiple-inheritance ttk method-resolution-order python-3.x

我对某些 Python 类中的多重继承的设计有一些疑问。

问题是我想扩展 ttk 按钮。这是我最初的建议(我省略了缩短方法中的所有源代码,除了init方法):

import tkinter as tk
import tkinter.ttk as ttk

class ImgButton(ttk.Button):
    """
    This has all the behaviour for a button which has an image
    """
    def __init__(self, master=None, **kw):
        super().__init__(master, **kw)
        self._img = kw.get('image')

    def change_color(self, __=None):
        """
        Changes the color of this widget randomly
        :param __: the event, which is no needed
        """
        pass

    def get_style_name(self):
        """
        Returns the specific style name applied for this widget
        :return: the style name as a string
        """
        pass

    def set_background_color(self, color):
        """
        Sets this widget's background color to that received as parameter
        :param color: the color to be set
        """
        pass

    def get_background_color(self):
        """
        Returns a string representing the background color of the widget
        :return: the color of the widget
        """
        pass

    def change_highlight_style(self, __=None):
        """
        Applies the highlight style for a color
        :param __: the event, which is no needed
        """
        pass
Run Code Online (Sandbox Code Playgroud)

但后来我意识到我还想要这个 ImgButton 的子类,如下所示:

import tkinter as tk
import tkinter.ttk as ttk

class MyButton(ImgButton):
    """
    ImgButton with specifical purpose
    """

    IMG_NAME = 'filename{}.jpg'
    IMAGES_DIR = os.path.sep + os.path.sep.join(['home', 'user', 'myProjects', 'myProject', 'resources', 'images'])
    UNKNOWN_IMG = os.path.sep.join([IMAGES_DIR, IMG_NAME.format(0)])
    IMAGES = (lambda IMAGES_DIR=IMAGES_DIR, IMG_NAME=IMG_NAME: [os.path.sep.join([IMAGES_DIR, IMG_NAME.format(face)]) for face in [1,2,3,4,5] ])()

    def change_image(self, __=None):
        """
        Changes randomly the image in this MyButton
        :param __: the event, which is no needed
        """
        pass

    def __init__(self, master=None, value=None, **kw):
        # Default image when hidden or without value

        current_img = PhotoImage(file=MyButton.UNKNOWN_IMG)
        super().__init__(master, image=current_img, **kw)
        if not value:
            pass
        elif not isinstance(value, (int, Die)):
            pass
        elif isinstance(value, MyValue):
            self.myValue = value
        elif isinstance(value, int):
            self.myValue = MyValue(value)
        else:
            raise ValueError()
        self.set_background_color('green')
        self.bind('<Button-1>', self.change_image, add=True)


    def select(self):
        """
        Highlights this button as selected and changes its internal state
        """
        pass

    def toggleImage(self):
        """
        Changes the image in this specific button for the next allowed for MyButton
        """
        pass
Run Code Online (Sandbox Code Playgroud)

继承权感觉很自然,符合他的观点。当我注意到 ImgButton 中的大多数方法对于我将来可能创建的任何小部件都可重用时,问题就出现了。

所以我正在考虑制作一个:

class MyWidget(ttk.Widget):
Run Code Online (Sandbox Code Playgroud)

将所有有助于小部件颜色的方法放入其中,然后我需要 ImgButton 继承自 MyWidget 和 ttk.Button:

class ImgButton(ttk.Button, MyWidget):  ???

or

class ImgButton(MyWidget, ttk.Button):  ???
Run Code Online (Sandbox Code Playgroud)

编辑:我也希望我的对象是可记录的,所以我做了这个类:

class Loggable(object):
    def __init__(self) -> None:
        super().__init__()
        self.__logger = None
        self.__logger = self.get_logger()

        self.debug = self.get_logger().debug
        self.error = self.get_logger().error
        self.critical = self.get_logger().critical
        self.info = self.get_logger().info
        self.warn = self.get_logger().warning


    def get_logger(self):
        if not self.__logger:
            self.__logger = logging.getLogger(self.get_class())
        return self.__logger

    def get_class(self):
        return self.__class__.__name__
Run Code Online (Sandbox Code Playgroud)

所以现在:

class ImgButton(Loggable, ttk.Button, MyWidget):  ???

or

class ImgButton(Loggable, MyWidget, ttk.Button):  ???

or

class ImgButton(MyWidget, Loggable, ttk.Button):  ???

# ... this could go on ...
Run Code Online (Sandbox Code Playgroud)

我来自 Java,我不知道多重继承的最佳实践。我不知道应该如何以最佳顺序对父母进行排序,也不知道如何对设计这种多重继承有用。

我搜索了该主题,发现了很多解释 MRO 的资源,但没有找到关于如何正确设计多重继承的信息。我不知道我的设计是否错误,但我认为感觉很自然。

如果您能提供一些建议以及有关此主题的一些链接或资源,我将不胜感激。

非常感谢。

mad*_*tyn 5

这些天我一直在阅读有关多重继承的内容,并且学到了很多东西。我在最后链接了我的来源、资源和参考文献。

我的主要和最详细的来源是《Fluent python》一书,我发现这本书可以在线免费阅读。

这描述了具有多重继承的方法解析顺序和设计场景以及完成它的步骤:

  1. 识别并分离接口代码。定义方法但不一定具有实现的类(这些类应该被重写)。这些通常是 ABC(抽象基类)。他们为创建“IS-A”关系的子类定义类型

  2. 识别并分离 mixin 的代码。mixin 是一个类,它应该带来一系列相关的新方法实现以在子级中使用,但没有定义正确的类型。按照这个定义,ABC 可以是 mixin,但反之则不然。mixin 既不定义也不定义接口,也不定义类型

  3. 当要使用 ABC 或类以及 mixins 继承时,您应该只继承一个具体的超类,以及几个 ABC 或 mixins:

例子:

class MyClass(MySuperClass, MyABC, MyMixin1, MyMixin2):
Run Code Online (Sandbox Code Playgroud)

就我而言:

class ImgButton(ttk.Button, MyWidget):
Run Code Online (Sandbox Code Playgroud)
  1. 如果某些类的组合特别有用或频繁,您应该将它们加入到具有描述性名称的类定义下

例子:

 class Widget(BaseWidget, Pack, Grid, Place):
     pass
Run Code Online (Sandbox Code Playgroud)

我认为 Loggable 是一个 Mixin,因为它收集了功能的便捷实现,但没有定义真正的类型。所以:

class MyWidget(ttk.Widget, Loggable): # May be renamed to LoggableMixin
Run Code Online (Sandbox Code Playgroud)
  1. 优先考虑对象组合而不是继承:如果您可以想到通过将类保存在属性中而不是扩展它或继承它来使用类的任何方式,那么您应该避免继承。

    Google 图书中的“流利的 python”(第 12 章)

    超级就是超级

    超级有害

    超级的其他问题

    奇怪的超级行为