新聞中心
Python編程語(yǔ)言作為一款功能強(qiáng)大的面向?qū)ο箝_源編程語(yǔ)言,其應(yīng)用特點(diǎn)比較突出,極大的方便了開發(fā)人員的應(yīng)用。在學(xué)習(xí)的過(guò)程中,我們可以從相關(guān)的實(shí)踐中去積累經(jīng)驗(yàn)來(lái)熟練掌握這一語(yǔ)言的應(yīng)用技巧。比如今天為大家介紹的Python應(yīng)用技巧的相關(guān)內(nèi)容就是一個(gè)比較重要的經(jīng)驗(yàn)。

創(chuàng)新互聯(lián)公司專注于企業(yè)成都全網(wǎng)營(yíng)銷、網(wǎng)站重做改版、南岸網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、html5、商城建設(shè)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁(yè)設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為南岸等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
Python應(yīng)用技巧1. self, cls 不是關(guān)鍵字
在python里面,self, cls 不是關(guān)鍵字,完全可以使用自己寫的任意變量代替實(shí)現(xiàn)一樣的效果
代碼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.
結(jié)論 : self和cls只是python中約定的寫法,本質(zhì)上只是一個(gè)函數(shù)參數(shù)而已,沒有特別含義。
任何對(duì)象調(diào)用方法都會(huì)把把自己作為該方法中的第一個(gè)參數(shù),傳遞到函數(shù)中。(因?yàn)樵趐ython中萬(wàn)物都是對(duì)象,所以當(dāng)我們使用Class.method()的時(shí)候,實(shí)際上的第一個(gè)參數(shù)是我們約定的cls)
Python應(yīng)用技巧2. 類的定義可以動(dòng)態(tài)修改
代碼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類中的變量和函數(shù)定義, 實(shí)例化的instance有了不同的行為特征。
Python應(yīng)用技巧3. decorator
decorator是一個(gè)函數(shù), 接收一個(gè)函數(shù)作為參數(shù), 返回值是一個(gè)函數(shù)
代碼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)
上面是一個(gè)比較典型的應(yīng)用
以常用的@classmethod為例
正常的使用方法是
代碼4
- class C:
- @classmethod
- def foo(cls, y):
- print "classmethod", cls, y
- class C: @classmethod def foo(cls, y): print "classmethod", cls, y
以上就是我們?yōu)榇蠹医榻B的有關(guān)Python應(yīng)用技巧的相關(guān)內(nèi)容。
分享文章:常用Python應(yīng)用技巧內(nèi)容分析
分享網(wǎng)址:http://fisionsoft.com.cn/article/dpggssp.html


咨詢
建站咨詢
