[英]How to undo “assert” in python?
在早期的功能中,讓我們稱之為a
,我必須確保a
函數不會產生太小的答案(比方說,答案必須大於10)。 但是后來,在第二個函數b
(使用函數a
作為其輸入之一)中,如果被修改的相同答案小於先前的assert
語句,則可以。
有沒有辦法做到這一點?
當函數b
產生一個太小的答案時,我試圖保存答案在變量中的小,但是當我運行doctest時我仍然遇到斷言錯誤。
def grade_on_project(student_project_score, max_score, overall_score):
project_grade = student_project_score / max_project_score
assert project_grade > 0.6 # (student fails the class if any of their scores on a project are too low)
overall_score +=student_project_score
return overall_score
def who_fails_first(operation, person1, person2)
if (operation(person1, max_score, person1) <= 150 and (operation(person2, max_score, overall_score) > 150:
print(student 1 failed)
if (operation(person2, max_score, overall_score) <= 150 and (operation(person1, max_score, overall_score) > 150:
print(student 2 failed)
who_fails_first(grade_on_project, 5, 9)
斷言不應該用於實現某些代碼的邏輯。 為什么? 因為你無法保證他們真的被提升了!
$python -c 'assert False'
Traceback (most recent call last):
File "<string>", line 1, in <module>
AssertionError
$python -O -c 'assert False' # doesn't raise an error!
$
-O
選項用於“優化”。 但它也刪除了所有斷言
assert
也應該被用於調試 ,檢查在一個良好的書面程序不應該發生的情況。
如果要以某種方式處理特殊輸入,則應使用異常 :
def grade_on_project(student_project_score, max_score, overall_score):
project_grade = student_project_score / max_project_score
if project_grade > 0.6:
raise ValueError('Student fails if at least one project grade is too low.')
overall_score +=student_project_score
return overall_score
或者您可以編寫一個自定義異常,例如:
class StudentFailed(ValueError):
def __init__(self, message, grade):
super(StudentFailed, self).__init__(message)
self.grade = grade
並將if
更改為:
if project_grade > 0.6:
raise StudentFailed('One project has grade too low.', project_grade)
然后,當您捕獲異常時,您仍然可以通過異常的grade
屬性訪問使其失敗的grade
。
如果您不想在特定情況下引發異常,可以添加一個參數,例如low_grade_is_ok
並將該函數修改為:
def grade_on_project(student_project_score, max_score,
overall_score, low_grade_is_ok=False):
project_grade = student_project_score / max_project_score
if not low_grade_is_ok and project_grade > 0.6:
raise ValueError('Student fails if at least one project grade is too low.')
overall_score +=student_project_score
return overall_score
然后在您不想引發異常的函數中,可以使用low_grade_is_ok=True
調用它,在這種情況下不會引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.