【发布时间】:2021-08-12 11:11:39
【问题描述】:
编辑
建议在 cmets 中继承,但这已经完成,我添加了额外的代码 sn-p 来显示。
在__init__ 之外初始化实例变量有一些类似的问题,其中实例变量在另一个def 函数(方法)内的类中进一步初始化。这个问题不是那些问题的重复。
我有三个类都在def __init__ 之后声明相同的self.xxxx 实例变量:
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, parent, title=title)
如何将这些代码行拆分为一个全局函数,调用该函数来初始化变量?我正在寻找一种类似于 bash .(源命令)或 C #include 命令的技术,除了变量不会来自另一个文件,只是当前文件(模块)中的一个全局函数。
仅供参考,我正在为 ShowInfo、AskQuestion、AskString 等的 tkinter simpledialog 类包装器寻找一致性和代码减少。
【问题讨论】:
-
创建一个你的三个类继承自的基类?
-
如果三个类都具有相同的 init ,则创建一个类然后继承它
-
参考这个link
-
@NikhilSingh 感谢您的链接。但是继承已经被使用,我更新了问题以显示代码。
-
@NikhilSingh 请添加答案。我很乐意接受并投票!
标签: python class initialization instance-variables