1 不要为函数的参数赋值为空列表,不然结果可能在意料之外
def FindPath(result=[]):
result.append(1)
print(result)
FindPath()
FindPath()
FindPath()
#输入结果如下:
[1]
[1, 1]
[1, 1, 1]
#正确的写法为:
def FindPath():
result=[]
result.append(1)
print(result)
FindPath()
FindPath()
FindPath()
#输出结果如下:
[1]
[1, 1]
[1, 1, 1]
#正确的写法为:
def FindPath():
result=[]
result.append(1)
print(result)
FindPath()
FindPath()
FindPath()
#输出结果如下:
[1]
[1]
[1]
2 也不要把含有值的列表作为函数默认参数
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def __init__(self,mycourse=["math"]): #假设每人都要学数学
self.mycourse=mycourse
def addmycourse(self,course_name):
self.mycourse.append(course_name)
print(self.mycourse)
a=Solution()
a.addmycourse("Chinese")
b=Solution()
b.addmycourse("English")
#输出
#['math', 'Chinese']
#['math', 'Chinese', 'English']
#总之,禁止将列表赋值为函数参数的初始默认值