在 Python 类之外初始化实例变量 编辑

问题描述

编辑

评论中建议继承,但是这已经完成,我已经添加了额外的代码片段来显示


__init__ 之外初始化实例变量有一些类似的问题,其中实例变量在另一个 def 函数方法)内的类中进一步初始化。这个问题不是那些问题的重复。

我有三个类都在 self.xxxx 之后声明了相同的 def __init__ 实例变量:

class AskQuestion(simpledialog.Dialog):
    """ Prepends "\n" to text passed.
        Appends "\n\nAre you sure?\n" to text passed.
        Allows text to be highlighted and copied to clipboard with CTRL+C.
        Blocks other windows from getting focus
        MON_FONTSIZE is temporary font size until configuration file set up.
    """

    def __init__(self,parent,title=None,text=None,confirm='yes',align='center',thread=None,icon='warning'):
        self.confirm = confirm      # Append "Are you sure?" line?
        self.align = align          # data (text lines) alignment
        self.thread = thread        # The thread run before button click
        self.loop_no = 1            # Loop counter (not used yet)
        self.data = text            # data (text lines) for text Box
        self.text = None            # TextBox widget
        self.icon = icon            # Warning,Error,Info,Question icons
        try:
            self.font = (None,MON_FONTSIZE)
        except NameError:
            self.font = (None,10)

        # Shared functions
        self.wait_window = wait_window_func
        #self.body = body(self,parent)
        #self.body = body

        simpledialog.Dialog.__init__(self,title=title)

如何将这些代码行分拆成一个全局函数,该函数调用以初始化变量?我正在寻找一种类似于 bash .(源命令)或 C #include 命令的技术,除了变量不会来自另一个文件,只是当前文件(模块).

仅供参考,我正在为 ShowInfo、AskQuestion、AskString 等的 tkinter simpledialog 类包装器寻找一致性和代码减少。

解决方法

在您的类共享 init 方法的情况下,您可以通过继承它们来减少代码,就像这样

class A(B):

其中B是父类,同样根据问题可以继承多个类,像这样

class A(B,C):

我提供了一个通用的答案,以避免与评论中的讨论相同