是的,Python 的 assert 語句可以用于驗證對象的狀態。assert 語句用于檢查一個條件是否為真,如果為假,則會引發 AssertionError 異常。這可以用于確保代碼中的某些條件滿足特定要求,從而避免潛在的錯誤。
例如,假設你有一個類 Person,它具有 name 和 age 兩個屬性,你可以使用 assert 語句來驗證這些屬性的值是否合法:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def check_status(self):
assert isinstance(self.name, str), "Name must be a string"
assert isinstance(self.age, int), "Age must be an integer"
assert self.age >= 0, "Age must be non-negative"
person = Person("Alice", 30)
person.check_status() # This will pass without any assertion errors
invalid_person = Person(123, -5)
invalid_person.check_status() # This will raise an AssertionError with the message "Name must be a string"
在這個例子中,check_status 方法使用 assert 語句來確保 name 是一個字符串,age 是一個非負整數。如果這些條件不滿足,將引發相應的 AssertionError 異常。