# 带有默认参数的函数在定义的时候就被计算了
def extendList(val, list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print("list1 = %s" % list1)
print("list2 = %s" % list2)
print( "list3 = %s" % list3)
list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']
# 由于闭包延迟,会寻找闭包内最近的参数,解决方案可以用生成器
def multipliers():
return [lambda x : i * x for i in range(4)]
print([m(2) for m in multipliers()])
[6, 6, 6, 6]
#被使用之后不会被父类的修改改变
class Parent(object):
x = 1
class Child1(Parent):
pass
class Child2(Parent):
pass
print( Parent.x, Child1.x, Child2.x)
Child1.x = 2
print( Parent.x, Child1.x, Child2.x)
Parent.x = 3
print( Parent.x, Child1.x, Child2.x)
1 1 1
1 2 1
3 2 3
# /表示浮点数除法,//表示整数除法
def div1(x,y):
print("%s/%s = %s" % (x, y, x/y))
def div2(x,y):
print("%s//%s = %s" % (x, y, x//y))
div1(5,2)
div1(5.,2)
div2(5,2)
div2(5.,2.)
5/2 = 2.5
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0
# 切片不报IndexError错误,而是返回空列表
list = ['a', 'b', 'c', 'd', 'e']
print(list[10:])
[]
# 该方式是创建一个列表,同时包含五个引用
list = [ [ ] ] * 5
list # output?
list[0].append(10)
list # output?
list[1].append(20)
list # output?
list.append(30)
list # output?
[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30]
# 第一步先取偶数位置的数,接着筛选剔除掉所有的奇数
list = [1,3,5,8,10,13,18,36,78]
[x for x in list[::2] if x%2 == 0]
[10, 18, 78]
#
class DefaultDict(dict):
def __missing__(self, key):
return []
d = DefaultDict()
d['florp'] = 127