日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

对于python中的self,cls,decorator的理解

發布時間:2025/7/14 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 对于python中的self,cls,decorator的理解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. self, cls 不是關鍵字

在python里面,self, cls 不是關鍵字,完全可以使用自己寫的任意變量代替實現一樣的效果

代碼1

Python代碼
Code:

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)



2. 類的定義可以動態修改

代碼2

Code:

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有了不同的行為特征。


3. decorator

decorator是一個函數, 接收一個函數作為參數, 返回值是一個函數


代碼3

Python代碼
Code:

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

Python代碼
Code:

class C:
@classmethod
def foo(cls, y):
print "classmethod", cls, y

class C: @classmethod def foo(cls, y): print "classmethod", cls, y


這里有個疑惑的地方,不是很明白: 如果一個方法沒有使用@classmethod, 那么用Class.method()的方式,是會報錯的。但是@classmethod是個decorator, 那么它返回的也是一個函數,為什么這樣就可以直接被Class調用了呢?

from:http://www.cnblogs.com/eplussoft/

總結

以上是生活随笔為你收集整理的对于python中的self,cls,decorator的理解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。