# python 可變對象參數

``````def f(a, L=[]):
L.append(a)
return L

print(f(1))
print(f(2))
print(f(3))
``````
``````[1]
[1, 2]
[1, 2, 3]
``````

``````def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
``````

# 參數(args)

## 形參和實參

``````def test(a, b):# ab是形參
return a+b
test(a=1,b=2)# 1,2分別是a，b的實參
``````

## 默認參數

``````def test(a=1,b):# 如果調用參數時不給a賦值，則默認a=1
``````

## 不定長參數

### *args 單星號參數

*單星號參數實質是傳入一個元組

``````In [1]: def name(*args):
...:     print(args)

In [2]: name(1,2,3)
(1, 2, 3)
``````

### **kwargs 雙星號參數

``````In [1]: def test(**kwargs):
...:     for key, value in kwargs.items():
...:         print(key+"="+value)

In [2]: test(a="1",b="2")
a=1
b=2

In[3]: dic={"a"=1,"b"=2}
In[4]:  test(**dic)  # 注意理解**的意義
a=1
b=2

``````
``````In[6]: def test(*args,**kwargs):
...:     print(f"args: {args}")
...:     print(f"kwargs: {kwargs}")
...:
...: test(1,2,3,4,5,a=1,b=2,c=3,d=4,e=5)
...:
args: (1, 2, 3, 4, 5)
kwargs: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
``````

1.`*`參數,必須出現在`**`參數之前
2.Python中函數參數是引用傳遞（注意不是值傳遞）。對於不可變類型，因變量不能修改，所以運算不會影響到變量自身；而對於可變類型來說，則相反

# Positional-or-Keyword Arguments

`def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):`

``````>>> def standard_arg(arg): //直接通過位置傳參
...     print(arg)
...
>>> def pos_only_arg(arg, /):  //不能通過`arg=1`傳參,因爲規定是位置參數
...     print(arg)
...
>>> def kwd_only_arg(*, arg): //不能通過
...     print(arg)
...
>>> def combined_example(pos_only, /, standard, *, kwd_only):
...     print(pos_only, standard, kwd_only)
``````