# -*- coding:utf8 -*-
# 2-3 python把函数作为参数
import math
def add(x, y, f):
return f(x) + f(y)
print add(25, 9, math.sqrt)
# 2-4 python中map()函数
def format_name(s):
return s.title()
print map(format_name, ['adam', 'LISA', 'barT'])
# 2-5 python中reduce()函数
def prod(x, y):
return x * y
print reduce(prod, [2, 4, 5, 7, 12])
# 2-6 python中filter()函数
# s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。
import math
def is_sqr(x):
return math.sqrt(x)%1 == 0
print filter(is_sqr, range(1, 101))
# 2-7 python中自定义排序函数
# 如果 x 应该排在 y 的前面,返回 -1,如果 x 应该排在 y 的后面,返回 1。如果 x 和 y 相等,返回 0。
def cmp_ignore_case(s1, s2):
if s1.lower() < s2.lower():
return -1
if s1.lower() > s2.lower():
return 1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
# 2-8 python中返回函数
def calc_prod(lst):
def c_prod():
def prod(x, y):
return x * y
return reduce(prod, lst)
return c_prod
f = calc_prod([1, 2, 3, 4])
print f()
# 2-9 python中闭包
def count():
fs = []
for i in range(1, 4):
def f(i):
return lambda : i*i
fs.append(f(i))
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
# 2-10 python中匿名函数
print filter(lambda s:s and len(s.strip()) > 0, ['test', None, '', 'str', ' ', 'END'])
# 2-12 python中编写无参数decorator
import time
def performance(f):
def fn(x):
print 'call '+f.__name__+'() in '+time.strftime('%Y-%m-%d',time.localtime(time.time()))
return f(x)
return fn
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
# 2-13 python中编写带参数decorator
import time
def performance(unit):
def fn(f):
def fn1(x):
t1 = time.time()
t2 = time.time()
t = (t2 - t1)*1000 if unit =='ms' else (t2 - t1)
print 'call %s() in %f %s'%(f.__name__, t, unit)
return f(x)
return fn1
return fn
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
# 2-14 python中完善decorator
import time, functools
def performance(unit):
def perf_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kw):
t1 = time.time()
t2 = time.time()
t = (t2 - t1)*1000 if unit =='ms' else (t2 - t1)
print 'call %s() in %f %s'%(f.__name__, t, unit)
return f(*args, **kw)
return wrapper
return perf_decorator
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial.__name__
# 2-15 python中偏函数
import functools
sorted_ignore_case = functools.partial(sorted, key = str.lower)
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
# 3-2 python之导入模块
from os.path import isdir,isfile
print isdir(r'/data/webroot/resource/python')
print isfile(r'/data/webroot/resource/python/test.txt')
# 3-3 pyhton中动态导入模块
try:
import json
except ImportError:
import simplejson as json
print json.dumps({'python':2.7})
# 3-4 pyhton之使用__future__
from __future__ import unicode_literals
s = 'am I an unicode?'
print isinstance(s, unicode)
# 4-2 pyhton之定义类并创建实例
class Person(object):
pass
xiaoming = Person()
xiaohong = Person()
print xiaoming
print xiaohong
print xiaoming == xiaohong
# 4-3 python中创建实例属性
class Person(object):
pass
p1 = Person()
p1.name = 'Bart'
p2 = Person()
p2.name = 'Adam'
p3 = Person()
p3.name = 'Lisa'
L1 = [p1, p2, p3]
L2 = sorted(L1, key = lambda x:x.name)
print L2[0].name
print L2[1].name
print L2[2].name
# 4-4 python中初始化实例属性
class Person(object):
def __init__(self, name, sex, birth, job):
self.name = name
self.sex = sex
self.birth = birth
self.job = job
xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student')
print xiaoming.name
print xiaoming.job
# 4-5 python中访问限制
class Person(object):
def __init__(self, name, score):
self.name = name
self.__score = score
p = Person('Bob', 59)
print p.name
try :
print p.__score
except AttributeError:
print 'attributeerror'
# 4-6 python中创建类属性
class Person(object):
count = 0
def __init__(self, name):
self.name = name
Person.count += 1
p1 = Person('Bob')
print Person.count
p2 = Person('Alice')
print Person.count
p3 = Person('Tim')
print Person.count
# 4-7 python中类属性和实例属性名字冲突
class Person(object):
__count = 0
def __init__(self, name):
self.name = name
Person.__count +=1
print Person.__count
p1 = Person('Bob')
p2 = Person('Alice')
try:
print Person.__count
except AttributeError:
print AttributeError
# 4-8 python中定义实例方法
class Person(object):
def __init__(self, name, score):
self.name = name
self.__score = score
def get_grade(self):
if self.__score >= 90:
return 'A'
elif self.__score >= 60:
return 'B'
else:
return 'C'
p1 = Person('Bob', 90)
p2 = Person('Alice', 65)
p3 = Person('Tim', 48)
print p1.get_grade()
print p2.get_grade()
print p3.get_grade()
# 4-9 python中方法也是属性
import types
def fn_get_grade(self):
if self.score >= 80:
return 'A'
if self.score >= 60:
return 'B'
return 'C'
class Person(object):
def __init__(self, name, score):
self.name = name
self.score = score
p1 = Person('Bob', 90)
p1.get_grade = types.MethodType(fn_get_grade, p1, Person)
print p1.get_grade()
#
class Person(object):
def __init__(self, name, score):
self.name = name
self.score = score
self.get_grade = lambda: 'A'
p1 = Person('Bob', 90)
print p1.get_grade
print p1.get_grade()
# 4-10 python中定义类方法
class Person(object):
__count = 0
@classmethod
def how_many(cls):
return cls.__count
def __init__(self, name):
self.nae = name
Person.__count += 1
print Person.how_many()
p1 = Person('Bob')
print Person.how_many()
# 4-11 python中继承一个类
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Teacher(Person):
def __init__(self, name, gender, course):
super(Teacher, self).__init__(name, gender)
self.course = course
t = Teacher('Alice', 'Female', 'English')
print t.name
print t.course
# 5-3 python中判断类型
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
class Teacher(Person):
def __init__(self, name, gender, course):
super(Teacher, self).__init__(name, gender)
self.course = course
t = Teacher('Alice', 'Female', 'English')
print isinstance(t, Person)
print isinstance(t, Student)
print isinstance(t, Teacher)
print isinstance(t, object)
# python中多态
import json
class Students(object):
def read(self):
return r'["Tim", "Bob", "Alice"]'
s = Students()
print json.load(s)
# 5-5 python中多重继承
class Person(object):
pass
class Student(Person):
pass
class Teacher(Person):
pass
class SkillMixin(object):
pass
class BasketballMixin(SkillMixin):
def skill(self):
return 'basketball'
class FootballMixin(SkillMixin):
def skill(self):
return 'football'
class BStudent(Student, BasketballMixin):
pass
class FTeacher(Teacher, FootballMixin):
pass
s = BStudent()
print s.skill()
t = FTeacher()
print t.skill()
# 5-6 python中获取对象信息
# kw传入一个dict,因此需要获取kye和values
#dir()返回的属性是字符串列表,如果已知一个属性名称,要获取或者设置对象的属性,就需要用 getattr() 和 setattr( )函数了
class Person(object):
def __init__(self, name, gender, **kw):
self.name = name
self.gender = gender
for k, v in kw.items():
setattr(self, k, v)
p = Person('Bob', 'Male', age=18, course='Python')
print p.age
print p.course
# 6-2 python中__str__和__repr__
# __str__()用于显示给用户,而__repr__()用于显示给开发人员
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
def __str__(self):
return '(Student:%s, %s, %d)' % (self.name, self.gender, self.score)
__repr__ = __str__
s = Student('Bob', 'male', 88)
print s
# 6-3 python中__cmp__
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if self.score < s.score:
return 1
elif self.score > s.score:
return -1
else:
if self.name < s.name:
return -1
else:
return 1
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print
sorted(L)
# 6-4 pyhton中__len__
class Fib(object):
def __init__(self, num):
self.num = num
self.fibo = [0, 1]
i = 2
while i < self.num:
self.fibo.append(self.fibo[i - 2] + self.fibo[i - 1])
i = i + 1
def __str__(self):
return str(self.fibo)
def __len__(self):
return len(self.fibo)
f = Fib(10)
print
f
print
len(f)
# 6-6 python中类型转换
class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __int__(self):
return self.p // self.q
def __float__(self):
return self.p / self.q
print float(Rational(7, 2))
print float(Rational(1, 3))
# 6-7 python中@property
class Student(object):
def __init__(self, name, score):
self.name = name
self.__score = score
@property
def score(self):
return self.__score
@score.setter
def score(self, score):
if score < 0 or score > 100:
raise ValueError('invalid score')
self.__score = score
@property
def grade(self):
if self.__score >= 80:
return 'A'
elif self.__score >= 60:
return 'B'
else:
return 'C'
s = Student('Bob', 59)
print s.grade
s.score = 60
print s.grade
s.score = 99
print s.grade
# 6-8 python中__slots__
# __slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。
class Person(object):
__slots__ = ('name', 'gender')
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
__slots__ = ('name', 'gender', 'score')
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
s = Student('Bob', 'male', 59)
s.name = 'Tim'
s.score = 99
print s.score
# 6-9 python中__call__
class Fib(object):
def __call__(self,num):
L = [0,1]
i = 2
while i < num:
L.append(L[i-2]+L[i-1])
i=i+1
return L
f = Fib()
print f(10)