更简洁的方式来编写这个try / except语句? [英] cleaner way to write this try/except statement?

查看:84
本文介绍了更简洁的方式来编写这个try / except语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要查看的代码是NumbersValidator类中的try语句,

只需几行。这是一个干净的写作方式吗?即是否可以

获得所有这些退货声明?这是一个很好用的尝试?等等


谢谢。


---------------------- ------


import wx

class NumbersValidator(wx.PyValidator):


def __init__ (个体经营):

wx.PyValidator .__ init __(self)


def克隆(个体经营):

返回NumbersValidator()


def验证(自我,父):

text_ctrl = self.GetWindow()

text = text_ctrl.GetValue()


试试:

如果不是text或int(text)< = 0:

wx.MessageBox(''Enter一个有效的时间。'','''无效的时间


输入'',wx.OK | wx.ICON_ERROR)

返回False

else:

返回True

除了ValueError,错误:

wx.MessageBox(''输入有效时间。'', ''输入的时间无效'',

wx.OK | wx.ICON_ERROR)

返回False


def TransferToWindow(自我):

返回True


def TransferFromWindow(个体经营) :

返回True

类定时器(wx.Frame):


def __init __(个体经营):

wx.Frame .__ init __(self,None,wx.ID_ANY,''Timer'',

style = wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER

^ wx .MAXIMIZE_BOX)

self.panel = wx.Panel(self)


mainSizer = wx.BoxSizer(wx.VERTICAL)

inputSizer = wx.BoxSizer(wx.HORIZONTAL)

self.progress = wx.Gauge(self.panel,wx.ID_ANY,100,size =(300,

20))

self.status = wx.StaticText(self.panel,wx.ID_ANY,''输入时间。'')

prompt = wx.StaticText(self.panel,wx.ID_ANY,''等待的时间:'')

self.input = wx.TextCtrl(self.panel,wx.ID_ANY,size =(20, 20),

validator = NumbersValidator())

self.start = wx.Button(self.panel,wx.ID_ANY,''Start'')

self.reset = wx.Button(self.panel,wx.ID_ANY,''重置'')

self.reset.Disable()

self.sound = wx.S ound(r''C:\ Windows \ Media \ notify.wav'')

self.timer = wx.Timer(self)


mainSizer.Add(self.progress,flag = wx.ALIGN_CENTER | wx.ALL ^

wx.BOTTOM,

border = 10)

mainSizer.Add(self.status,flag = wx.ALIGN_CENTER | wx.ALL,

border = 10)

mainSizer.Add(inputSizer,flag = wx.ALIGN_CENTER | wx.BOTTOM,

border = 10)

inputSizer.Add(prompt,flag = wx.ALIGN_CENTER)

inputSizer.Add(self.input,flag = wx.ALIGN_CENTER | wx.LEFT |

wx.RIGHT,

border = 5)

inputSizer.Add(self.start,flag = wx.ALIGN_CENTER)

inputSizer.Add(self.reset,flag = wx.ALIGN_CENTER)

self.Bind(wx.EVT_TEXT_ENTER,self.OnStart,self.input)

self.Bind(wx.EVT_BUTTON,self.OnStart,self.start)

self.Bind(wx.EVT_TIMER,self.OnTimer,self.timer)

self.Bind(wx.EVT_BUTTON,self.OnReset,self.reset)


self.panel.SetSizer(mainSizer)

mainSizer.Fit(self)


def OnStart(自我,事件):

if self.panel.Validate():

self.time = int (self.input.GetValue())

self.minutes_passed = 1

self.minutes_remaining = self.time - 1

self.start.Disable()

self .input.Disable()

self.reset.Enable()

self.status.SetLabel('%s分钟剩余。''%self。时间)

self.timer.Start(1000)

def OnReset(自我,事件):

if self.timer .IsRunning():

self.timer.Stop()

self.input.Clear()

self.input.Enable()

self.start.Enable()

self.reset.Disable()

self.status.SetLabel(''输入新时间。'')

self.progress.SetValue(0)

self.minutes_passed = 1


def OnTimer(self,事件):

if self.minutes_remaining!= 0:

self.progress.SetValue(self.minutes_passed * 100 / self.time)

self.status.SetLabel('%s分钟剩余。''%

self.minutes_remaining)

self.minutes_passed + = 1

self.minutes_remaining - = 1

else:

self.timer.Stop()

self.progress.SetValue(self.minutes_passed * 100 / self.time)

self.status.SetLabel('%s分钟已经过去。''%self.time)

wx.Sound.Play(self.sound)

类MyApp(wx.App):


def OnInit(个体经营):

frame =计时器()

self.SetTopWindow(框架)

frame.Show()

返回True

if __name__ ==''__ main__'':

app = MyApp(假)

app.MainLoop()

The code to look at is the try statement in the NumbersValidator class,
just a few lines down. Is this a clean way to write it? i.e. is it okay
to have all those return statements? Is this a good use of try? Etc.

Thanks.

----------------------------

import wx
class NumbersValidator(wx.PyValidator):

def __init__(self):
wx.PyValidator.__init__(self)

def Clone(self):
return NumbersValidator()

def Validate(self, parent):
text_ctrl = self.GetWindow()
text = text_ctrl.GetValue()

try:
if not text or int(text) <= 0:
wx.MessageBox(''Enter a valid time.'', ''Invalid time

entered'', wx.OK | wx.ICON_ERROR)
return False
else:
return True
except ValueError, error:
wx.MessageBox(''Enter a valid time.'', ''Invalid time entered'',
wx.OK | wx.ICON_ERROR)
return False

def TransferToWindow(self):
return True

def TransferFromWindow(self):
return True
class Timer(wx.Frame):

def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, ''Timer'',
style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER
^ wx.MAXIMIZE_BOX)
self.panel = wx.Panel(self)

mainSizer = wx.BoxSizer(wx.VERTICAL)
inputSizer = wx.BoxSizer(wx.HORIZONTAL)

self.progress = wx.Gauge(self.panel, wx.ID_ANY, 100, size=(300,
20))
self.status = wx.StaticText(self.panel, wx.ID_ANY, ''Enter a time.'')
prompt = wx.StaticText(self.panel, wx.ID_ANY, ''Time to wait:'')
self.input = wx.TextCtrl(self.panel, wx.ID_ANY, size=(20, 20),
validator=NumbersValidator())
self.start = wx.Button(self.panel, wx.ID_ANY, ''Start'')
self.reset = wx.Button(self.panel, wx.ID_ANY, ''Reset'')
self.reset.Disable()
self.sound = wx.Sound(r''C:\Windows\Media\notify.wav'')
self.timer = wx.Timer(self)

mainSizer.Add(self.progress, flag=wx.ALIGN_CENTER | wx.ALL ^
wx.BOTTOM,
border=10)
mainSizer.Add(self.status, flag=wx.ALIGN_CENTER | wx.ALL,
border=10)
mainSizer.Add(inputSizer, flag=wx.ALIGN_CENTER | wx.BOTTOM,
border=10)
inputSizer.Add(prompt, flag=wx.ALIGN_CENTER)
inputSizer.Add(self.input, flag=wx.ALIGN_CENTER | wx.LEFT |
wx.RIGHT,
border=5)
inputSizer.Add(self.start, flag=wx.ALIGN_CENTER)
inputSizer.Add(self.reset, flag=wx.ALIGN_CENTER)

self.Bind(wx.EVT_TEXT_ENTER, self.OnStart, self.input)
self.Bind(wx.EVT_BUTTON, self.OnStart, self.start)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.Bind(wx.EVT_BUTTON, self.OnReset, self.reset)

self.panel.SetSizer(mainSizer)
mainSizer.Fit(self)

def OnStart(self, event):
if self.panel.Validate():
self.time = int(self.input.GetValue())
self.minutes_passed = 1
self.minutes_remaining = self.time - 1
self.start.Disable()
self.input.Disable()
self.reset.Enable()
self.status.SetLabel(''%s minute(s) remaining.'' % self.time)
self.timer.Start(1000)

def OnReset(self, event):
if self.timer.IsRunning():
self.timer.Stop()
self.input.Clear()
self.input.Enable()
self.start.Enable()
self.reset.Disable()
self.status.SetLabel(''Enter a new time.'')
self.progress.SetValue(0)
self.minutes_passed = 1

def OnTimer(self, event):
if self.minutes_remaining != 0:
self.progress.SetValue(self.minutes_passed * 100 / self.time)
self.status.SetLabel(''%s minute(s) remaining.'' %
self.minutes_remaining)
self.minutes_passed += 1
self.minutes_remaining -= 1
else:
self.timer.Stop()
self.progress.SetValue(self.minutes_passed * 100 / self.time)
self.status.SetLabel(''%s minute(s) have elapsed.'' % self.time)
wx.Sound.Play(self.sound)
class MyApp(wx.App):

def OnInit(self):
frame = Timer()
self.SetTopWindow(frame)
frame.Show()
return True
if __name__ == ''__main__'':
app = MyApp(False)
app.MainLoop()

推荐答案

John Salerno写道:
John Salerno wrote:

要查看的代码是NumbersValidator类中的try语句,

只需几行。这是一个干净的写作方式吗?即是否可以

获得所有这些退货声明?这是一个很好用的尝试?等等
The code to look at is the try statement in the NumbersValidator class,
just a few lines down. Is this a clean way to write it? i.e. is it okay
to have all those return statements? Is this a good use of try? Etc.



我把它清理了一下并做了这个,但当然这不行。

这是错的在类中创建函数(不是方法)的方法吗?


def验证(self,parent):

text_ctrl = self.GetWindow()

text = text_ctrl.GetValue()

尝试:

如果不是text或int(text)< = 0:

error_message()

返回False

else:

返回True

除了ValueError:

error_message()

返回False


@staticmethod

def error_message():

wx.MessageBox(''输入有效时间。'',''输入的时间无效'',

wx.OK | wx.ICON_ERROR)

I cleaned it up a little and did this, but of course this doesn''t work.
Is this the wrong way to create a function (not method) within a class?

def Validate(self, parent):
text_ctrl = self.GetWindow()
text = text_ctrl.GetValue()

try:
if not text or int(text) <= 0:
error_message()
return False
else:
return True
except ValueError:
error_message()
return False

@staticmethod
def error_message():
wx.MessageBox(''Enter a valid time.'', ''Invalid time entered'',
wx.OK | wx.ICON_ERROR)


John Salerno写道:
John Salerno wrote:

John Salerno写道:
John Salerno wrote:

要查看的代码是NumbersValidator类中的try语句,

只需几行。这是一个干净的写作方式吗?即是否可以

获得所有这些退货声明?这是一个很好用的尝试?等等。
The code to look at is the try statement in the NumbersValidator class,
just a few lines down. Is this a clean way to write it? i.e. is it okay
to have all those return statements? Is this a good use of try? Etc.



我把它清理了一下并做了这个,但当然这不行。

这是错的在类中创建函数(不是方法)的方法吗?


def验证(self,parent):

text_ctrl = self.GetWindow()

text = text_ctrl.GetValue()

尝试:

如果不是text或int(text)< = 0:

error_message()

返回False

else:

返回True

除了ValueError:

error_message()

返回False


@staticmethod

def error_message():

wx.MessageBox(''输入有效时间。'',''输入的时间无效'',

wx.OK | wx.ICON_ERROR)


I cleaned it up a little and did this, but of course this doesn''t work.
Is this the wrong way to create a function (not method) within a class?

def Validate(self, parent):
text_ctrl = self.GetWindow()
text = text_ctrl.GetValue()

try:
if not text or int(text) <= 0:
error_message()
return False
else:
return True
except ValueError:
error_message()
return False

@staticmethod
def error_message():
wx.MessageBox(''Enter a valid time.'', ''Invalid time entered'',
wx.OK | wx.ICON_ERROR)



你的缩进看起来很像。你的error_message()函数应该与

相同的缩进与Validate()方法的其余部分相同

(即与try语句相同,text_ctrl = ...陈述。)


如果这不是发布在这里的工件那么你需要

更正。


此外,没有必要将函数声明为staticmethod,因为它不是


除此之外它对我来说还不错,但我可能错过了一些东西。


和平,

~西蒙

Your indentation looks off. Your error_message() function should be at
the same indentation as the rest of the body of the Validate() method
(i.e. same as the try statement, "text_ctrl = ..." statements.)

If that''s not an artifact of posting it here then you''ll need to
correct that.

Also, there''s no need to declare the function a staticmethod, since it
isn''t.

Other than that it looks ok to me, but I might have missed something.

Peace,
~Simon


Simon Forman写道:
Simon Forman wrote:

John Salerno写道:
John Salerno wrote:

John Salerno写道:
John Salerno wrote:

要查看的代码是NumbersValidator类中的try语句,

只需几行下。这是一个干净的写作方式吗?即是否可以

获得所有这些退货声明?这是一个很好用的尝试?等等
The code to look at is the try statement in the NumbersValidator class,
just a few lines down. Is this a clean way to write it? i.e. is it okay
to have all those return statements? Is this a good use of try? Etc.



我把它清理了一下并做了这个,但当然这不行。

这是错的在类中创建函数(不是方法)的方法吗?


def验证(self,parent):

text_ctrl = self.GetWindow()

text = text_ctrl.GetValue()

尝试:

如果不是text或int(text)< = 0:

error_message()

返回False

else:

返回True

除了ValueError:

error_message()

返回False


@staticmethod

def error_message():

wx.MessageBox(''输入有效时间。'',''输入的时间无效'',

wx.OK | wx.ICON_ERROR)

I cleaned it up a little and did this, but of course this doesn''t work.
Is this the wrong way to create a function (not method) within a class?

def Validate(self, parent):
text_ctrl = self.GetWindow()
text = text_ctrl.GetValue()

try:
if not text or int(text) <= 0:
error_message()
return False
else:
return True
except ValueError:
error_message()
return False

@staticmethod
def error_message():
wx.MessageBox(''Enter a valid time.'', ''Invalid time entered'',
wx.OK | wx.ICON_ERROR)



你的缩进厕所ks off。你的error_message()函数应该与

相同的缩进与Validate()方法的其余部分相同

(即与try语句相同,text_ctrl = ...陈述。)


如果这不是发布在这里的工件那么你需要

更正。


此外,没有必要将函数声明为staticmethod,因为它不是


除此之外它对我来说还不错,但我可能错过了一些东西。


Your indentation looks off. Your error_message() function should be at
the same indentation as the rest of the body of the Validate() method
(i.e. same as the try statement, "text_ctrl = ..." statements.)

If that''s not an artifact of posting it here then you''ll need to
correct that.

Also, there''s no need to declare the function a staticmethod, since it
isn''t.

Other than that it looks ok to me, but I might have missed something.



也许我确实错过了一些东西:你真的试图制作一个静态的

方法吗?比如说,除了Validate()

方法之外,还能调用它吗?


在这种情况下,你的缩进仍然(显然)关闭,但

error_message()方法(静态方法仍然是我认为的一种方法,但我可能是错误的b $ b)应该与其他任何方法处于相同的缩进级别/>
方法,当你调用它时,你必须在实例对象(''self。'',如果你是从另一个方法中调用它的
)之前添加它。


A级(对象):

def meth(self,arg):

self.func(arg)


@staticmethod

def func(arg):

print arg


a = A ()


a.func(" hi")

a.meth(" world。")

#打印



世界。


HTH,

~Simon


Maybe I did miss something: Are you actually trying to make a static
method? Say, to be able to call it elsewhere than just the Validate()
method?

In that case, your indentation is still (apparently) off, but the
error_message() method (a staticmethod is still a method I think, but I
could be wrong) should be at the same indentation level as any other
method, and you have to prepend the instance object (''self.'' if you''re
calling it from inside another method) to it when you call it.

class A(object):
def meth(self, arg):
self.func(arg)

@staticmethod
def func(arg):
print arg

a = A()

a.func("hi")
a.meth("world.")
# prints
hi
world.

HTH,
~Simon


这篇关于更简洁的方式来编写这个try / except语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆