2010-11-01 71 views
2

我有这个tkinter GUI,我需要从条目中获取值并进行比较。 self.hystInt.get()是访问Entry中字符串变量的字符串的方式。 *我必须为每个变量写这个,所以最终看起来真的很难看。更好的方式来写这个if语句?

if (self.hystInt.get().isdigit() and int(self.hystInt.get()) >= 200 and int(self.hystInt.get()) <= 500): 
+0

你有多少个条目?表驱动设计可能比重复*难看的代码块更合适。 – 2010-11-01 21:06:38

+2

,而这段代码的起源可能是一个tkinter程序,这个问题实际上与tkinter无关。我建议删除tkinter标签。问题和答案对于任何需要'get()'来检索值的对象同样有效。 – 2010-11-01 21:17:59

+0

这里的一个可能性是使用Python更高级的描述符以“=”语句自动获取变量“get”和“set” - 就像内置的函数中的“property”一样 - 但我会专注于getters在这种情况下也是设置者来说明验证。如果你想以这种方式去感受,请直接告诉我。 – jsbueno 2010-11-01 22:46:13

回答

1

至少,你可以使用Python的异常比较语法是这样的:

if (self.hystInt.get().isdigit() and (200 <= int(self.hystInt.get()) <= 500)): 
+0

我认为原始代码更具可读性。这段代码需要一个人停下来并在心里解析代码。 – 2010-11-01 21:16:23

+2

@Bryan:就在你不了解Python并且太用于其他编程语言的时候。 Math学习逻辑的方式使用Python允许的相同语法:'x jsbueno 2010-11-01 22:42:11

+0

@jsbueno:我同意在某些情况下更容易阅读,特别是当它的形式为'x 2010-11-01 23:13:37

10
def validate(num): 
    try: 
     return 200 <= int(num) <= 500 
    except ValueError: 
     return False 

简单就是好!

+2

对于Python方式+1,最好是请求宽恕而不是允许。 – Davy8 2010-11-01 21:38:35

1

做到这一点。

try: 
    hystInt= int(self.hystInt.get()) 
    if 200 <= hystInt <= 500: 
     Valid. 
    else: 
     Out of bounds. 
except ValueError, e: 
    Not even a number. 
0

为了减少繁琐的编码,你可以沿着这些路线做一些事情:

valid_hystInt = lambda self, low, high: (
    self.hystInt.get().isdigit() and (low <= int(self.hystInt.get()) <= high) 
) 

class Class: 
    hystInt = HystInt() # or whatever 

    def some_method(self): 
     if valid_hystInt(self, 200, 500): 
      pass # use it 

或可能更加普遍:

valid_int_field = lambda field, low, high: (
    field.get().isdigit() and (low <= int(field.get()) <= high) 
) 

class Class: 
    hystInt = HystInt() # or whatever 

    def some_method(self): 
     if valid_int_field(self.hystInt, 200, 500): 
      pass # use it 
1

怎么样一个临时变量?我认为真正的问题(无论是在可读性方面还是在性能方面)(非常)都是你要三次调用get()方法。

histint = self.hystInt.get() 
if (histint.isdigit() and 
    (200 <= int(histint) <= 500)) 
相关问题