函数式变成:支持高阶函数(接受函数为参数的函数),支持闭包
1.python把函数作为参数
import mathdef add(x, y, f): return f(x) + f(y)print add(25, 9, math.sqrt) //这里引用的,math函数库里的求平方根函数sqrt()2.python中map()函数 //这里引用了高阶函数map(f,list)会把list中的每个值赋给函数f进行输出
首字母大写,后面的小写def format_name(s): str1 = s[0:1].upper()+s[1:].lower() return str1print map(format_name, ['adam', 'LISA', 'barT'])3.python中reduce()函数:还可以接收第三个至作为初值
对list中的值进行积的运算,reduce每次只能送进两个参数def prod(x, y): return x*yprint reduce(prod, [2, 4, 5, 7, 12])4.python中filter()函数:filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list
注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' '),如下:import mathdef is_sqr(x):
return math.sqrt(x)%1 == 0 //这里不用isinstance的原因:math.sqrt()函数求的值都为float型print filter(is_sqr, range(1,101))5.python中自定义排序函数sorted()
def cmp_ignore_case(s1, s2): s1=s1.lower() s2=s2.lower() if s1 < s2: //可以用cmp(s1.lower(),s2.lower())代替 return -1 if s1 > s2: return 1 if s1 == s2: return 0print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)6.python中返回函数
它接收一个list,返回一个函数,返回函数可以计算参数的乘积。def calc_prod(lst): def prod(x,y): return x * y def lazy_prod(): return reduce(prod,lst) return lazy_prodf = calc_prod([1, 2, 3, 4])print f()7.python中闭包:像这种内层函数引用了外层函数的变量(参数也算变量),然后返回内层函数的情况,称为闭包(Closure)
def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fsf1, f2, f3 = count()
print f1(),f2(),f3() //这里输出的是9,9,9,因为上面的i是变量,最后一次输出为3*************************def count(): fs = [] for i in range(1, 4): def f(j): //这个函数的作用就是把变量变成定值 def g(): return j**2 return g r = f(i) fs.append(r) return fsf1, f2, f3 = count()
print f1(), f2(), f3()8.python中匿名函数lambda
lambda s:s and len(s.strip()) > 0相当于:def is_not_empty(s): return s and len(s.strip()) > 0---------------------------------------print filter(lambda s:s and len(s.strip()) > 0, ['test', None, '', 'str', ' ', 'END'])9.python中编写无参数decorator
如果模块是被导入,__name__的值为模块名字如果模块是被直接执行,__name__的值为’__main__’返回执行函数的时间差:import timedef performance(f): def fn(*args): t1 = time.time() r = f(*args) t2 = time.time() print 'call %s () in %fs' %(f.__name__, (t2 - t1)) return r return fn@performancedef factorial(n): return reduce(lambda x,y: x*y, range(1, n+1))print factorial(10)10.python中编写带参数decorator
import timedef performance(unit):
def performance_decorator(f): def wrapper(*args): t1 = time.time() r = f(*args) t2 = time.time() t = (t2 -t1)*1000 if unit == 'ms' else (t2-t1) print 'call %s() in %f %s' % (f.__name__, t, unit) return r return wrapper return performance_decorator@performance('ms')
def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1))print factorial(10)
11.python完善decorator之functools
import time, functoolsdef performance(unit):
def per_decorator(f): @functools.wraps(f) def wrapper(*args,**kw): t1 = time.time() r = f(*args,**kw) t2 = time.time() t = (t2-t1)*1000 if unit == 'ms' else (t2-t1) print "call %s in %f %s" %(f.__name__,t,unit) return r return wrapper return per_decorator@performance('ms')
def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1))print factorial.__name__
12.python中偏函数---functools.partial可以把一个参数多的函数变成一个参数少的新函数,少的参数需要在创建时指定默认值,这样,新函数调用的难度就降低了。
import functoolssorted_ignore_case = functools.partial(sorted,cmp = lambda s1,s2:cmp(s1.lower(),s2.lower()))print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
******************************
包,模块:包就是文件夹,模块就是文件每个包都有一个_init_文件******************************13.包,模块的引入import osimport os.pathfrom os import pathfrom os.path import isdir, isfile14.python中动态导入模块
有的时候,两个不同的模块提供了相同的功能,比如 StringIO 和 cStringIO 都提供了StringIO这个功能。StringIO 是纯Python代码编写的,而 cStringIO 部分函数是 C 写的,因此 cStringIO 运行速度更快。利用ImportError错误,我们经常在Python中动态导入模块:try: from cStringIO import StringIOexcept ImportError: from StringIO import StringIOtry 的作用是捕获错误,并在捕获到指定错误时执行 except 语句。15.python之使用__future__
from __future__ import unicode_literalss = 'am I an unicode?'
t = b'am I an str?'print isinstance(s, unicode)print isinstance(t,str) **********************面向对象编程***************************16.python之定义类并创建实例
class Person(object): passxiaoming = Person()xiaohong = Person()print xiaoming
print xiaohongprint xiaoming == xiaohong17.python中创建实例属性
class Person(object): passp1 = Person()
p1.name = 'Bart'p2 = Person()
p2.name = 'Adam'p3 = Person()
p3.name = 'Lisa'L1 = [p1, p2, p3]
L2 = sorted(L1,lambda p1,p2: cmp(p1.name,p2.name))print L2[0].name
print L2[1].nameprint L2[2].name18.python中初始化实例属性__init__
class Person(object): def __init__(self,name,sex,birthday,**kw): //init可以用别的变量代替,但是默认是self self.name = name self.sex = sex self.birthday = birthday for k,v in kw.iteritems(): setattr(self,k,v) //相当于self.k = v xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student')print xiaoming.name
print xiaoming.job19.python中访问限制
ython对属性权限的控制是通过属性名来实现的,如果一个属性由双下划线开头(__),该属性就无法被外部访问class Person(object): def __init__(self, name, score): self.name = name self.__score = scorep = Person('Bob', 59)
print p.name
try: //以"__xxx__"定义的属性在Python的类中被称为特殊属性 print p.__score //以单下划线开头的属性"_xxx"虽然也可以被外部访问,但是,按照习惯,他们不应该被外部访问。except: print 'attributeError'20.python中创建类属性class Person(object): count = 0 def __init__(self,name): //这里count属于类的属性,不重置,初始化函数会重置并给类的属性+1 self.name = name Person.count += 1p1 = Person('xiaoming')
print Person.countp2 = Person('xiaohong')
print Person.count21.python中类属性和实例属性名字冲突怎么办
当实例属性和类属性重名时,实例属性优先级高,它将屏蔽掉对类属性的访问。class Person(object): __count = 0 def __init__(self, name): self.name = name Person.__count += 1 print Person.__countp1 = Person("xiaoming")
p2 = Person("xiaohong")try:
print Person.countexcept: print 'Error'22.python中定义实例方法# -*- coding: utf-8 -*-class Person(object): """docstring for Person"""def __init__(self, name,grade):
self.__name = name self.__grade = grade def get_grade(self): if self.__grade > 75: return u'A-优秀' if self.__grade >60: return u'B-及格' return u'C-不及格'p1 = Person('Bob', 90)
print p1.get_grade()p2 = Person('Alice', 65)print p2.get_grade()p3 = Person('Tim', 48)print p3.get_grade()23.python中方法也是属性
p1.get_grade调用的是函数,而p1.get_grade()则调用的是这个函返回的结果,即:方法调用。函数调用不需要传入 self,但是方法调用需要传入 self。(self可省)class Person(object):def __init__(self, name, score):
self.name = name self.score = score self.get_grade = lambda: 'A' //lambda相当于def get_grade(): // return 'A'p1 = Person('Bob', 90)
print p1.get_gradeprint p1.get_grade()----------------------------------# -*- coding: utf-8 -*-#给一个实例绑定一个方法import types
def fn_get_grade(self):
if self.grade >= 90: return 'a' elif self.grade >= 60: return 'b' else: return 'c'class Person(object):
"""docstring for Person""" def __init__(self, name,grade): self.name = name self.grade = gradep1 = Person('xiaoming',61)
p2 = Person('xiaohong',33)p3 = Person('zhangsan',91)try:
print p1.get_gradeexcept: print 'error'p1.get_grade = types.MethodType(fn_get_grade,p1,Person) //types.MethodType() 把一个函数变为一个方法:print p1.get_grade()24.python中定义类方法
在class中定义的全部是实例方法,实例方法第一个参数 self 是实例本身。方法的第一个参数将传入类本身,通常将参数名命名为 cls,上面的 cls.count 实际上相当于 Person.count。class Person(object):__count = -1
@classmethod def how_many(cls): cls.__count += 1 return cls.count def __init__(self,name): self.name = nameprint Person.how_many()
p1 = Person('Bob')
print Person.how_many()
25.python中继承一个类
class Person(object): """docstring for """ def __init__(self, name,gender): self.name = name self.gender = genderclass Teacher(Person): """docstring for Teacher""" def __init__(self,name,gender,course): super(Teacher, self).__init__(name,gender) self.course = coursep1 = Teacher('Alice','female','English')
print p1.nameprint p1.course26.pytho判断类型:
print isinstance(t,Person)print isinstance(t,Student)print isinstance(t,Teacher)print isinstance(t,object)27.python中多态:s 是Student类型,它实际上拥有自己的 whoAmI()方法以及从 Person继承的 whoAmI方法,但调用 s.whoAmI()总是先查找它自身的定义,如果没有定义,则顺着继承链向上查找,直到在某个父类中找到为止。
class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender def whoAmI(self): return 'I am a Person, my name is %s' % self.nameclass Student(Person):
def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score = score def whoAmI(self): return 'I am a Student, my name is %s' % self.nameclass Teacher(Person):
def __init__(self, name, gender, course): super(Teacher, self).__init__(name, gender) self.course = course def whoAmI(self): return 'I am a Teacher, my name is %s' % self.name在一个函数中,如果我们接收一个变量 x,则无论该 x 是 Person、Student还是 Teacher,都可以正确打印出结果:def who_am_i(x):
print x.whoAmI()p = Person('Tim', 'Male')
s = Student('Bob', 'Male', 88)t = Teacher('Alice', 'Female', 'English')who_am_i(p)
who_am_i(s)who_am_i(t)运行结果:I am a Person, my name is Tim
I am a Student, my name is BobI am a Teacher, my name is Alice28.python中多重继承
除了从一个父类继承外,Python允许从多个父类继承,称为多重继承。多重继承的继承链就不是一棵树了,它像这样:
class A(object):
def __init__(self, a): print 'init A...' self.a = aclass B(A):
def __init__(self, a): super(B, self).__init__(a) print 'init B...'class C(A):
def __init__(self, a): super(C, self).__init__(a) print 'init C...'class D(B, C):
def __init__(self, a): super(D, self).__init__(a) print 'init D...'看下图:---
| A | --- / \ / \--- ---
| B | | C | --- --- \ /\ / \ / --- | D | ---29.python中获取对象信息a = 123print type(a)输出为:<type 'int'>
# -*- coding: utf-8 -*-
class Person(object):def __init__(self, name, gender, **kw): #这里必须用**kw
self.name = name self.gender = gender for k,v in kw.iteritems(): setattr(self,k,v) #设置属性值p = Person('Bob', 'Male', course='Python')
print getattr(p,'age',500) #这里的属性age必须加上单引号,这里的500是当没有age参数是输出的默认值print p.course30.python中 __str__和__repr__ class Person(object): def __init__(self,name,gender): self.name = name self.gender = genderclass Student(Person):
"""docstring for Student""" def __init__(self,name,gender,score): super(Student, self).__init__(name,gender) self.score = score def __str__(self): return '(Student:%s,%s,%s)' %(self.name,self.gender,self.score) __repr__ = __str__s = Student('xiaoming','male',88)
print s31.实例之sorted()---自定义__cmp__函数
# -*- coding: utf-8 -*-class Student(object): """docstring for Person""" def __init__(self, name,score): self.name = name self.score = score def __str__(self): return '(Student:%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: return cmp(self.name,s.name) # if self.score == s.score: # return cmp(self.name, s.name) # return -cmp( self.score,s.score)L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]print sorted(L)32.python中 __len__
class Fib(object): """docstring for Fib""" def __init__(self, num): a,b,L = 0,1,[] for n in range(num): L.append(a) a,b = b,a+b self.numbers = L def __str__(self): return str(self.numbers) def __len__(self): return len(self.numbers) __repr__ = __str__print Fib(10)print len(Fib(10))33.python中数学运算
# -*- encoding: utf-8 -*-class Rational(object): """docstring for Rational""" def __init__(self, p, q): self.p = p self.q = q def __add__(self,r): return Rational(self.p * r.q + self.q * r.p , self.q * r.q) def __sub__(self,r): return Rational(self.p * r.q - self.q * r.p , self.q * r.q) def __mul__(self,r): return Rational(self.p * r.p, self.q * r.q) def __div__(self,r): return Rational(self.p * r.q, self.q * r.p) def __str__(self): #下面一段是对分数的约分 if self.p < self.q: if self.p%2 == 0 and self.q%2 == 0: return '%s/%s' %(self.p/2, self.q/2) else: return '%s/%s' %(self.p, self.q) else: if self.p%2 == 0 and self.q%2 == 0: return '%s/%s' %(self.p/2, self.q/2) __repr__ = __str__r1 = Rational(1, 2)r2 = Rational(1, 4)print r1 + r2print r1 - r2print r1 * r2print r1 / r234.python中类型转换
class Rational(object): def __init__(self, p, q): self.p = p self.q = qdef __int__(self):
return self.p // self.qdef __float__(self):
return self.p * 1.0 / self.q #这里的//是整除,7//2.0 == 3.0,而7/2.0 == 3.5print float(Rational(7, 2))
print float(Rational(1, 3))35.python中 @property
---------------类属性:(r1是一个对象)print r1.__dict__ ---------->{'q': 2, 'p': 1}print r1.__dict__['p']---------->1 //输出属性p,即print r1.p---------------property将一些代码(get_temperature和set_temperature)附加到成员属性(temperature)的访问入口.任何获取temperature值的代1property(fget=None, fset=None, fdel=None, doc=None)这里,fget是一个获取属性值的函数,fset是一个设置属性值的函数,fdel是一个删除属性的函数,doc是一个字符串(类似于注释)。从函数实现上看,这些函数参数都是可选的。所以,可以按照如下的方式简单的创建一个property对象。 >>> property()<property object at 0x0000000003239B38>12>>> property()<property object at 0x0000000003239B38>Property对象有三个方法,getter(), setter()和delete(),用来在对象创建后设置fget,fset和fdel。这就意味着,这行代码:temperature = property(get_temperature,set_temperature)可以被分解为: # make empty propertytemperature = property()# assign fgettemperature = temperature.getter(get_temperature)# assign fsettemperature = temperature.setter(set_temperature)************装饰器详解http://blog.csdn.net/u013696062/article/details/51065406************class Student(object): """docstring for Student""" def __init__(self, name, score): self.name = name self.__score = score@property
def score(self): return self.__core @score.setter def score(self,value): if value < 0 or value > 100: raise NameError('noinvaild value') #抛出异常,如果使用raise的话,后面的语句不能执行 else: self.__score = value @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.grades.score = 60
print s.grades.score = 99
print s.grade36.python中 __slots__:__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存
class Person(object):__slots__ = ('name', 'gender')
def __init__(self, name, gender):
self.name = name self.gender = genderclass Student(Person):
__slots__ = ('name','gender','score')
def __init__(self, name, gender, score):
super(Student,self).__init__(name, gender) self.score = score def __str__(self): return '%s:%s:%s' %(self.name, self.gender, self.score) __repr__ = __str__s = Student('Bob', 'male', 59)print s s.name = 'Tim's.score = 99print s.score36.python中 __call__将类的实例直接当成函数调用
class Fib(object): """docstring for Fib""" def __init__(self): passdef __call__(self, num):
a, b, L = 0, 1, [] for x in xrange(num): L.append(a) a, b = b, a + b return Lnumbers = Fib()print numbers(10)