常用Python應用技巧內容分析
Python編程語言作為一款功能強大的面向對象開源編程語言,其應用特點比較突出,極大的方便了開發人員的應用。在學習的過程中,我們可以從相關的實踐中去積累經驗來熟練掌握這一語言的應用技巧。比如今天為大家介紹的Python應用技巧的相關內容就是一個比較重要的經驗。
Python應用技巧1. self, cls 不是關鍵字
在python里面,self, cls 不是關鍵字,完全可以使用自己寫的任意變量代替實現一樣的效果
代碼1
- class MyTest:
- myname = 'peter'
- def sayhello(hello):
- print "say hello to %s" % hello.myname
- if __name__ == "__main__":
- MyTest().sayhello()
- 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
- 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)
- 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
- 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)
- 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
- class C:
- @classmethod
- def foo(cls, y):
- print "classmethod", cls, y
- class C: @classmethod def foo(cls, y): print "classmethod", cls, y
以上就是我們為大家介紹的有關Python應用技巧的相關內容。
【編輯推薦】