我有一个实现模型和视图的程序。
我希望模型进行一些处理,如果出现问题,请向视图返回警告。
现在,我希望将警告作为一种异常传递出去,因此,如果我将GUI作为视图,则可以轻松地创建一个消息框或类似的东西来显示警告,但不会中断程序流。
有什么办法可以实现?
[注意:我知道Python中的warnings
模块,但是我不知道我是否可以将那些警告作为不会中断程序流的异常来传递。
相关代码:
class Model():
def __init__(self):
try:
with open(some_file) as file:
self.file = file.readlines()
except FileNotFoundError:
# I don't want the Model to print the message here
# print("Warning: File not found, continuing with defaults")
# I want a warning to be passed up to the view
self.file = 'some piece of data'
raise FileNotFoundError(error_msg)
class View():
def __init__(self):
try:
self.model = Model()
except FileNotFoundError:
# I want to catch the warning here and display it
# but if I catch an exception here, Python will complain that
# self.model was not initialized correctly when I use it later
谢谢
异常用于委派错误处理,不与调用方通信。代替重新引发异常,向对象添加另一个属性,指示file
属性中的数据是否经过硬编码。
例如,
class Model():
def __init__(self):
self.hard_coded = False
try:
with open(some_file) as file:
self.file = file.readlines()
except FileNotFoundError:
self.source = True
self.file = 'some piece of data'
class View():
def __init__(self):
self.model = Model()
if self.hard_coded:
print("Warning: File not found, continuing with defaults")
或者,您可以使用值为error_msg
或字符串的None
属性,以便在视图不是None
时打印视图。