# 可变数据类型不能作为python函数的参数

def foo(a=[]):
a.append(1)
return a
print(foo())
print(foo())
print(foo())

[1]
[1, 1]
[1, 1, 1]

print(id(foo()))
print(id(foo()))
print(id(foo()))

140344852133960
140344852133960
140344852133960

b = [1,2]
def test(place=b):
place.append(1)
return place
print(b)
print(test())
print(b)
print(test())
print(b)

[1, 2]
[1, 2, 1]
[1, 2, 1]
[1, 2, 1, 1]
[1, 2, 1, 1]

c = [1,2,3]
d = c
print(id(c))
print(id(d))

140344851860104
140344851860104

d.append(4)
print(d)
print(c)
print(id(d))
print(id(c))

[1, 2, 3, 4]
[1, 2, 3, 4]
140344851860104
140344851860104

python中一切皆对象。函数也是对象，可以这么理解，一个函数是一个被它自己定义而执行的对，;默认参数是一种"成员数据"，所以它们的状态和其他对象一样,会随着每一次调用而改变。

def foo(a=None):
if a is None:
a = []
a.append(1)
return a
print(foo())
print(foo())
print(foo())

[1]
[1]
[1]

sentinel = object()

def myfunc(value=sentinel):
if value is sentinel:
value = expression
# use/modify value here

arr = [1,2,3]
res = []
def permutation(arr,tmp=[]):
global res
if len(arr) == 0:
res.append(tmp)
return
for i in range(len(arr)):
tmp = tmp + [arr[i]]
newArr = arr[:i]+arr[i+1:]
permutation(newArr,tmp)
subset(arr,tmp=[])
print(res)

[[1, 2, 3], [1, 2, 3, 2], [1, 2, 1, 3], [1, 2, 1, 3, 1], [1, 2, 3, 1, 2], [1, 2, 3, 1, 2, 1]]

arr = [1,2,3]
res = []
def permutation(arr,tmp=[]):
global res
if len(arr) == 0:
res.append(tmp)
return
for i in range(len(arr)):
newTmp = tmp + [arr[i]]
newArr = arr[:i]+arr[i+1:]
permutation(newArr,newTmp)
subset(arr,tmp=[])
print(res)

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

posted @ 2020-10-17 19:27  西西嘛呦  阅读(21)  评论(0编辑  收藏