python中不要將列表作為函式引數預設值

2021-10-19 16:10:00 字數 837 閱讀 5210

​​​​​​​def findpath(result=): 

print(result)

findpath()

findpath()

findpath()

#輸入結果如下:

[1][1, 1]

[1, 1, 1]

#正確的寫法為:

def findpath():

result=

print(result)

findpath()

findpath()

findpath()

#輸出結果如下:

[1][1, 1]

[1, 1, 1]

class solution:

# 返回二維列表,內部每個列表表示找到的路徑

def __init__(self,mycourse=["math"]): #假設每人都要學數學

self.mycourse=mycourse

def addmycourse(self,course_name):

print(self.mycourse)

a=solution()

a.addmycourse("chinese")

b=solution()

b.addmycourse("english")

#輸出

#['math', 'chinese']

#['math', 'chinese', 'english']

#總之,禁止將列表賦值為函式引數的初始預設值

Python列表作為引數

在將列表作為引數傳遞給函式的時候,實際上是傳遞的引用。def ref someparameter 99 singers 阪井泉水 泰勒斯威夫特 阿黛爾 ref singers print singers 結果 阪井泉水 泰勒斯威夫特 阿黛爾 99 同時,將列表賦給乙個變數時,實際上是將列表的引用付給...

python中用列表作為佇列

佇列有 先進先出 的,這樣沒刪除或者是鄭加乙個元素,這樣就需要對原列表進行移動,這樣效率會比較低,就引入 collections.deque這樣可以提高效率 from collections import deque queue deque eric john michael print queue...

python中full函式 Python函式混亂

我正在學習 python.我有乙個函式readwrite filename,list filename的型別為string.list是乙個包含要在檔案中重寫的字串的列表.我有乙個簡單的函式呼叫,如下所示 fname hello.txt readwrite xx fname,datalist 我面臨的...