要測試Python中使用setattr
的正確性,你可以按照以下步驟進行:
setattr
修改。例如:class MyClass:
def __init__(self):
self.attribute1 = "value1"
self.attribute2 = "value2"
setattr
來修改類的屬性。例如:def modify_attributes(obj, attribute_name, new_value):
if hasattr(obj, attribute_name):
setattr(obj, attribute_name, new_value)
else:
raise AttributeError(f"Object does not have attribute '{attribute_name}'")
modify_attributes
函數按預期工作。例如:def test_modify_attributes():
obj = MyClass()
# Test modifying an existing attribute
modify_attributes(obj, "attribute1", "new_value1")
assert obj.attribute1 == "new_value1", f"Expected 'new_value1', got {obj.attribute1}"
# Test modifying another existing attribute
modify_attributes(obj, "attribute2", "new_value2")
assert obj.attribute2 == "new_value2", f"Expected 'new_value2', got {obj.attribute2}"
# Test modifying a non-existing attribute (should raise an AttributeError)
try:
modify_attributes(obj, "non_existing_attribute", "some_value")
except AttributeError as e:
assert str(e) == "Object does not have attribute 'non_existing_attribute'", f"Unexpected error message: {str(e)}"
else:
assert False, "Expected an AttributeError but none was raised"
print("All tests passed!")
setattr
的正確性。if __name__ == "__main__":
test_modify_attributes()
這樣,你就可以通過編寫和運行測試用例來確保setattr
在你的代碼中正確地修改了類的屬性。