注意传递参数的时候,不好传递空列表,不然有时会出现一些无法理解的问题
def add(a, b):
a += b
return a
class company(object):
def __init__(self, name, stuff=[]):
self.name = name
self.stuff = stuff
def add(self, stuff_name):
self.stuff.append(stuff_name)
def remove(self, stuff_name):
self.stuff.remove(stuff_name)
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
if __name__ == '__main__':
a = 1
b = 2
print(add(a, b))
print(a)
print(b)
a = [1, 2]
b = [3, 4]
print(add(a, b))
print(a)
print(b)
a = (1, 2)
b = (3, 4)
print(add(a, b))
print(a)
print(b)
com2 = company("com2")
com2.add("bobby")
print(com2.stuff)
com3 = company("com3")
com3.add("bobby5")
print(com2.stuff)
print(com3.stuff)
print(bad_append('1'))
print(bad_append('2'))
输出
3
1
2
[1, 2, 3, 4]
[1, 2, 3, 4]
[3, 4]
(1, 2, 3, 4)
(1, 2)
(3, 4)
['bobby']
['bobby', 'bobby5']
['bobby', 'bobby5']
['1']
['1', '2']
所以下次传列表参数的时候,记住不要传递[],而是可以传为None
如:
def bad_append(new_item, a_list=None):
if a_list == None:
a_list = []
a_list.append(new_item)
return a_list
这样就可以了。