Python基础部分学完之后,在进入其OOP部分前,先理解一下其装饰器这种结构,其功能可类比于Java中的面向切面编程,下面参见具体实例:
def log(f): def fn(x): print 'call ' + f.__name__ + '()...' return f(x) return fnprint '------------ 直接调 ----------- 'g = log(int)g('10010') # 只调不打印返回值print ''print g('10010') # 又调又打印输出结果print '------------ 装饰器 ----------- '@logdef myabs(x): if x < 0: return -x else: return xprint myabs(-17)# 下面是错误的装饰器调用# @log# def add(x,y):# return x + y# print add(4,8)print '----------- 修改装饰器以支持多参数 -----------'def log2(f): def fn(*args,**kv): print 'call ' + f.__name__ + '()...' return f(*args,**kv) return fn@log2def add(x,y): return x + yprint add(4,8)print '-------------------- 带参的装饰器 ------------------------'def log3(prefix): def log_decorator(f): def fn(*args,**kv): print '[%s] %s()...' % (prefix,f.__name__) return f(*args,**kv) return fn return log_decoratorprint '---- 普通调用 -----'def division(x,y): return x/ylog_decorator = log3('DEBUG')division = log_decorator(division)print division(18, 6)print '---- 装饰器调用 ----'@log3('DEBUG')def multiplication(a,b): return a * bprint multiplication(3, 4)
下面针对Python类中几个常见的特殊方法重写:
class Student(object): def __init__(self,name,score): self.name = name self.score = score def __str__(self): return '(Student: %s, %s)' % (self.name,self.score) def __cmp__(self,s): if self.name < s.name: return -1 elif self.name > s.name: return 1 else: return 0 def __call__(self,friend): print 'My name is %s...' % self.name print 'My friend is %s...' % friend.name print '------- basic info output ------------' John = Student('John',99)Alice = Student('Alice',85)print Johnprint Aliceprint '\n------------ special called -------------'John.gender = 'male'print 'changed: ' , John # 没打印出来新属性gender,因为自定义的__str__方法中没有print John.gender # 确实给John添加了新属性John(Alice)print '\n------------ instance sort --------------'L = [John,Alice]print sorted(L)print '\n------- print a sorted list -----------'mylist = [Student('Alice',85),Student('Bob',90),Student('Tom',100)]print sorted(mylist)