常用Python应用技巧内容分析

来源:岁月联盟 编辑:zhu 时间:2010-03-28

Python编程语言作为一款功能强大的面向对象开源编程语言,其应用特点比较突出,极大的方便了开发人员的应用。在学习的过程中,我们可以从相关的实践中去积累经验来熟练掌握这一语言的应用技巧。比如今天为大家介绍的Python应用技巧的相关内容就是一个比较重要的经验。

Python应用技巧1. self, cls 不是关键字

在python里面,self, cls 不是关键字,完全可以使用自己写的任意变量代替实现一样的效果

代码1

  1. class MyTest:   
  2. myname = 'peter'   
  3. def sayhello(hello):   
  4. print "say hello to %s" % hello.myname   
  5. if __name__ == "__main__":   
  6. MyTest().sayhello()   
  7. class MyTest: myname = 'peter' def sayhello(hello): print "say hello 
    to %s" % hello.myname if __name__ == "__main__": MyTest().sayhello() 

代码1中, 用hello代替掉了self, 得到的是一样的效果,也可以替换成java中常用的this.

结论 : self和cls只是python中约定的写法,本质上只是一个函数参数而已,没有特别含义。

任何对象调用方法都会把把自己作为该方法中的第一个参数,传递到函数中。(因为在python中万物都是对象,所以当我们使用Class.method()的时候,实际上的第一个参数是我们约定的cls)

Python应用技巧2. 类的定义可以动态修改

代码2

  1. class MyTest:   
  2. myname = 'peter'   
  3. def sayhello(self):   
  4. print "say hello to %s" % self.myname   
  5. if __name__ == "__main__":   
  6. MyTest.myname = 'hone'   
  7. MyTest.sayhello = lambda self,name: "I want say hello to %s" % name   
  8. MyTest.saygoodbye = lambda self,name: "I do not want say goodbye to %s" % name   
  9. print MyTest().sayhello(MyTest.myname)   
  10. print MyTest().saygoodbye(MyTest.myname)   
  11. class MyTest: myname = 'peter' def sayhello(self): print "say hello to %s" 
    % self.myname if __name__ == "__main__": MyTest.myname = 'hone' MyTest.sayhello 
    = lambda self,name: "I want say hello to %s" % name MyTest.saygoodbye = 
    lambda self,name: "I do not want say goodbye to %s" % name print MyTest().
    sayhello(MyTest.myname) print MyTest().saygoodbye(MyTest.myname) 

这里修改了MyTest类中的变量和函数定义, 实例化的instance有了不同的行为特征。

Python应用技巧3. decorator

decorator是一个函数, 接收一个函数作为参数, 返回值是一个函数

代码3

  1. def enhanced(meth):   
  2. def new(self, y):   
  3. print "I am enhanced"   
  4. return meth(self, y)   
  5. return new   
  6. class C:   
  7. def bar(self, x):   
  8. print "some method says:", x   
  9. bar = enhanced(bar)   
  10. def enhanced(meth): def new(self, y): print "I am enhanced" 
    return meth(self, y) return new class C: def bar(self, x): 
    print "some method says:", x bar = enhanced(bar) 

上面是一个比较典型的应用

以常用的@classmethod为例

正常的使用方法是

代码4

  1. class C:   
  2. @classmethod   
  3. def foo(cls, y):   
  4. print "classmethod", cls, y   
  5. class C: @classmethod def foo(cls, y): print "classmethod", cls, y 

以上就是我们为大家介绍的有关Python应用技巧的相关内容。


图片内容