错误案例分析:Python函数参数传递问题
在 Python 中,函数的参数传递主要分为两种方式:值传递和引用传递。
- 错误案例一:值传递导致数据丢失
def square(num):
return num ** 2
num = 5
squared_num = square(num) # 参数为原始数值
print(squared_num) # 输出 25,因为原数被复制而非修改
# 改变原变量 num
num = 10
print(squared_num) # 这时输出 100,尽管 num 变了
- 错误案例二:引用传递导致对象共享
class Person:
def __init__(self, name):
self.name = name
def update_person(person):
person.name = "Updated Name"
# 创建两个不同的人实例
person1 = Person("Alice")
person2 = Person("Bob")
# 通过引用传递,将 person1 更新为 updated_name
update_person(person1)
print(person2.name) # 输出 "Bob",因为 person2 的引用未被更新
# 改变原变量 person1,再次更新 person2
person1.name = "New Alice"
update_person(person1)
print(person2.name) # 输出 "Updated Name",因为 person2 仍引用了 person1 更新后的值
以上两种错误案例主要在于对 Python 参数传递方式的理解不足。在实际编程中,需要根据具体需求和场景选择合适的参数传递方式。
还没有评论,来说两句吧...