assert
是
assert x >= 0, 'x is less than zero'
好于或差于
if x < 0: raise Exception, 'x is less than zero'
if x < 0 raise error
try/except/finally
x
assert x < 0
当 x 在整个函数中小于零时,能够自动抛出错误。您可以使用类描述符。这是一个例子:
class LessThanZeroException(Exception): pass class variable(object): def __init__(self, value=0): self.__x = value def __set__(self, obj, value): if value < 0: raise LessThanZeroException('x is less than zero') self.__x = value def __get__(self, obj, objType): return self.__x class MyClass(object): x = variable() >>> m = MyClass() >>> m.x = 10 >>> m.x -= 20 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "my.py", line 7, in __set__ raise LessThanZeroException('x is less than zero') LessThanZeroException: x is less than zero