pythonself,cls,decorator的理解
來源:懂視網(wǎng)
責(zé)編:小采
時間:2020-11-27 14:39:22
pythonself,cls,decorator的理解
pythonself,cls,decorator的理解: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 % h
導(dǎo)讀pythonself,cls,decorator的理解: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 % h

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()
代碼1中, 用hello代替掉了self, 得到的是一樣的效果,也可以替換成java中常用的this.
結(jié)論 : self和cls只是python中約定的寫法,本質(zhì)上只是一個函數(shù)參數(shù)而已,沒有特別含義。
任何對象調(diào)用方法都會把把自己作為該方法中的第一個參數(shù),傳遞到函數(shù)中。(因?yàn)樵趐ython中萬物都是對象,所以當(dāng)我們使用Class.method()的時候,實(shí)際上的第一個參數(shù)是我們約定的cls)
2. 類的定義可以動態(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)
這里修改了MyTest類中的變量和函數(shù)定義, 實(shí)例化的instance有了不同的行為特征。
3. decorator
decorator是一個函數(shù), 接收一個函數(shù)作為參數(shù), 返回值是一個函數(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)
上面是一個比較典型的應(yīng)用
以常用的@classmethod為例
正常的使用方法是
代碼4
代碼如下:
class C:
@classmethod
def foo(cls, y):
print "classmethod", cls, y
這里有個疑惑的地方,不是很明白: 如果一個方法沒有使用@classmethod, 那么用Class.method()的方式,是會報錯的。但是@classmethod是個decorator, 那么它返回的也是一個函數(shù),為什么這樣就可以直接被Class調(diào)用了呢?
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
pythonself,cls,decorator的理解
pythonself,cls,decorator的理解: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 % h