Python传参误加()致返回数据异常的问题与解决方案
问题描述
我的AskQuestion函数在传入不带()的函数名self.refresh_play_top时运行正常:
answer = message.AskQuestion( self.loc_top, thread=self.refresh_play_top, align='left', icon='warning', title="Forget Location Confirmation", text=text)
但如果误加()传入函数调用结果thread=self.refresh_play_top()时,函数会返回损坏数据:
answer = message.AskQuestion( self.loc_top, thread=self.refresh_play_top(), align='left', icon='warning', title="Forget Location Confirmation", text=text)
当前AskQuestion函数内仅直接执行self.thread = thread,请问该如何修改?
解决方案
- 修改
self.refresh_play_top()函数,使其始终返回True或False(避免默认返回None); - 在
AskQuestion的__init__方法中添加参数校验逻辑:
def __init__(self, parent, text=None, confirm='yes', align='center', thread=None, icon='warning'): self.top_level = parent # Allows .after() calls self.confirm = confirm # Append "Are you sure?" line? self.align = align # data (text lines) alignment if thread is None: self.thread = None elif callable(thread): self.thread = thread # The thread run before button click else: print("message.py, CommonSelf, invalid thread= passed") self.thread = None
- 反复测试并修复问题。
内容的提问来源于stack exchange,提问作者WinEunuuchs2Unix
相关产品推荐
相关产品推荐

