编程中常见错误的正确实现 (Part 3)
本文件提供了 common_mistakes_part3.py
中常见错误的正确实现。
示例 1: 安全地使用 'eval'
不再使用 eval
,而是使用 ast.literal_eval
来更安全地评估用户输入。这可以防止执行任意代码。
示例 2: 在访问字典之前检查键是否存在
代码现在检查键是否存在于字典中,然后再尝试访问它,从而防止 KeyError
。
示例 3: 使用整数循环而不是浮点数
代码现在在 range
函数中使用整数,并缩放结果以实现类似浮点数的行为,从而避免 TypeError
。
示例 4: 使用修改状态的函数的返回值
代码现在捕获 update_list
函数的返回值,从而明确该函数修改列表并返回修改后的列表。
示例 5: 使用 __eq__ 比较具有自定义相等性的对象
MyClass
现在实现了 __eq__
方法,以基于对象的值而不是它们的标识来比较对象。
代码示例
# Corrected Implementations for Common Mistakes
# Example 1: Using 'eval' securely
# Instead of using eval, use ast.literal_eval for safer evaluation of user input.
import ast
def safe_evaluate(user_input):
try:
return ast.literal_eval(user_input)
except (ValueError, SyntaxError):
return "Invalid input"
# Example usage
user_input = input("Enter a Python literal (e.g., 1, 'hello', [1, 2]): ")
result = safe_evaluate(user_input)
print("Result:", result)
# Example 2: Checking for key existence before dictionary access
my_dict = {'a': 1, 'b': 2}
key = 'c'
if key in my_dict:
value = my_dict[key]
print("Value:", value)
else:
print(f"Key 'c' not found in dictionary")
# Example 3: Using a loop with integers instead of floating-point numbers
# Use integers and scale if necessary for floating-point-like behavior.
for i in range(10):
value = i / 10.0 # Scale to get 0.0, 0.1, ..., 0.9
print(value)
# Example 4: Using return values of functions that modify state
def update_list(lst):
lst.append(5)
return lst
my_list = [1, 2, 3]
updated_list = update_list(my_list) # Capture the return value
print("Updated list:", updated_list)
# Example 5: Comparing objects with custom equality using __eq__
class MyClass:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, MyClass):
return self.value == other.value
return False
obj1 = MyClass(10)
obj2 = MyClass(10)
if obj1 == obj2: # Now compares object value, not identity
print("Objects are equal")
else:
print("Objects are not equal")