python
中的assert
命令通常在代码调试中会被使用,它用来判断紧跟着的代码的正确性,如果满足条件(正确),万事大吉,程序自动向后执行,如果不满足条件(错误),会中断当前程序并产生一个AssertionError
错误。 它近似等同于如下代码:
if __debug__:
if not expression: raise AssertionError
比如我们计算一个实际问题,我们经历了一系列的计算后得到了一个时间t
值,这时我们就可以在代码中使用assert t >= 0
来对我们获取到的时间t
进行测试,如果t < 0
,则与实际问题矛盾,这时就会产生一个AssertionError
,我们就可以知道是我们的计算出现了问题,我们就可以回过头去修改前面的计算过程而不用再继续往下看了。可以让我们分段来检查自己书写的代码。
为了更好的了解assert
的用法,请看如下代码:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
assert x > 5
print(f"the value of x is: {x}")
if __name__ == "__main__":
main = Debug()
main.mainProgram()
"""
当我们输入6时,会打印出x的结果6
result:
Please input a integer: 6
the value of x is: 6
当我们输入5时,会被告知assert x > 5有问题,并且中断程序执行,产生AssertionError错误。
result:
assert x > 5
AssertionError
"""
上述代码完全等同于下面的代码:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
if x > 5:
print(f"the value of x is: {x}")
else:
raise AssertionError
if __name__ == "__main__":
main = Debug()
main.mainProgram()
然而这样的assert
报错提示并不完美,因为只是告知了assert x>5
这一行出现错误,并没有文字性的错误提示。如果assert
的内容比较复杂时,我们很可能会一时半会不知道错误的具体原因,这时我们应该采用assert
的拓展提示功能,拓展功能等同于代码:
if __debug__:
if not <expression1>: raise AssertionError, <expression2>
具体例子代码如下:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
assert x > 5, "the value of x should greater than 5"
print(f"the value of x is: {x}")
if __name__ == "__main__":
main = Debug()
main.mainProgram()
"""
我们输入5,代码会标注出错误的行,以及我们设置的错误提示信息
result:
assert x > 5, "the value of x should greater than 5"
AssertionError: the value of x should greater than 5
"""
至此,assert
的用法就基本结束了,但是我自己又探索了一下这个错误提示文字的运行机制。代码如下:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
assert x > 5, x <= 5
print(f"the value of x is: {x}")
if __name__ == "__main__":
main = Debug()
main.mainProgram()
"""
我们输入5,
result:
assert x > 5, x <= 5
AssertionError: True
"""
可以看到我们将assert
后面本应该出现的文字提示部分改为了一个表达式x <= 5
,这时的输出结果为AssertionError: True
,我们输入5
的时候assert x > 5
不符合条件,因此会报错并且输出后面我们添加的错误提示信息,但是现在的错误提示信息是一个表达式,5 <= 5
,表达式正确,表达式的结果应为True
,结合我们上一个给出的字符串的错误提示,我们可以推断,这个我们附加的错误提示其实相当于执行了一个print()
函数,在这个例子中,print(x < =5)
的结果就会在屏幕上打印一个True
。即上述代码等同于:
class Debug:
def mainProgram(self):
x = int(input("Please input a integer: "))
if x > 5:
print(f"the value of x is: {x}")
else:
print(x <= 5)
if __name__ == "__main__":
main = Debug()
main.mainProgram()
如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~