Python基础部分学完之后,在进入其OOP部分前,先理解一下其装饰器这种结构,其功能可类比于Java中的面向切面编程,下面参见具体实例:
def log(f): def fn(x): print 'call ' + f.__name__ + '()...' return f(x) return fn print '------------ 直接调 ----------- ' g = log(int) g('10010') # 只调不打印返回值 print '' print g('10010') # 又调又打印输出结果 print '------------ 装饰器 ----------- ' @log def myabs(x): if x < 0: return -x else: return x print 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 @log2 def add(x,y): return x + y print 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_decorator print '---- 普通调用 -----' def division(x,y): return x/y log_decorator = log3('DEBUG') division = log_decorator(division) print division(18, 6) print '---- 装饰器调用 ----' @log3('DEBUG') def multiplication(a,b): return a * b print 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 John print Alice print ' ------------ special called -------------' John.gender = 'male' print 'changed: ' , John # 没打印出来新属性gender,因为自定义的__str__方法中没有 print John.gender # 确实给John添加了新属性 John(Alice) print ' ------------ instance sort --------------' L = [John,Alice] print sorted(L) print ' ------- print a sorted list -----------' mylist = [Student('Alice',85),Student('Bob',90),Student('Tom',100)] print sorted(mylist)