# lambda

lambda x: x * x

def f(x):
return x * x

# map

map将传入的函数依次作用到序列的每个元素，并把结果作为新的list返回

def a(x):
return x*2
print map(a, [1, 2, 3, 4])
#结果
[2, 4, 6, 8]

or lambda

print map(lambda x: x*2, [1, 2, 3, 4])
#结果
[2, 4, 6, 8]

# reduce

reduce把结果继续和序列的下一个元素做累积计算

def b(x, y):
return x * y

print reduce(b, [1, 2, 3, 4])
#结果
24

or lambda

print reduce(lambda x, y: x * y, [1, 2, 3, 4])
#结果
24
#流程
1, 1*2 = 2
2, 2*3 = 6
3, 6*4 = 24


# filter

filter()函数用于过滤序列

def c(x):
return x>=2
print filter(c, [None, 1, 2, 3, 4])
#结果
[2, 3, 4]

or lambda

print filter(lambda x: x>=2, [None, 1, 2, 3, 4])
#结果
[2, 3, 4]

print filter(None, [None, 1, 2, 3, 4])
#结果
[1,2, 3, 4]

# sorted

print sorted([11, 21, 3, 4])
#结果
[3, 4, 11, 21]

class C1(object):
def __init__(self, age):
self.age = age

def __cmp__(self, y):
return self.age > y.age and 1 or -1

def __str__(self):
return str(self.age)

c1 = [C1(11), C1(21), C1(2), C1(1)]
print [c.age for c in c1]
#C1 必须实现__cmp__方法
c2 = sorted(c1)
c3 = sorted(c1, lambda x,y: x.age > y.age and 1 or -1)
print [c.age for c in c2]
print [c.age for c in c3]

# partial

functools.partial的作用就是，把一个函数的某些参数给固定住（也就是设置默认值），返回一个新的函数，调用这个新函数会更简单。

from functools import partial

class A1(object):
def __init__(self, name):
self.name = name

class B1(object):
def __init__(self, name):
self.name = name

a1 = A1("A1")
b1 = B1("B1")

def get_field(obj, field):
return getattr(obj, field)
c = partial(get_field, field="name")
d = partial(lambda obj, field: getattr(obj, field), field="name")

#get_field(a1, "name") == c == d
print get_field(a1, "name")
print c(a1)
print d(a1)

A1
A1
A1

# property


class D1(object):
def __init__(self, age):
self.__age = age

def get_age(self):
return self.__age

def set_age(self, age):
if not isinstance(age, int):
raise ValueError('age must be an integer!')
self.__age = age

d1 = D1(11)
print d1.get_age()
d1.set_age(22222)
print d1.get_age()


class D1(object):
def __init__(self, age):
self.__age = age

@property
def age(self):
return self.__age

@age.setter
def age(self, age):
if not isinstance(age, int):
raise ValueError('age must be an integer!')
self.__age = age

def get_age(self):
return self.__age

d1 = D1(11)
print d1.age
d1.age = 222
print d1.age
print d1.get_age()

or


class D1(object):
def __init__(self, age):
self.__age = age

def __set_age(self, age):
if not isinstance(age, int):
raise ValueError('age must be an integer!')
self.__age = age

def __get_age(self):
return self.__age

age = property(__get_age, __set_age)
del __get_age, __set_age

d1 = D1(11)
print d1.age
d1.age = 100
print d1.age