詳解Python中@staticmethod和@classmethod區(qū)別及使用示例代碼
本文主要介紹Python中,class(類)的裝飾器@staticmethod和@classmethod的使用示例代碼和它們的區(qū)別。
1、@staticmethod和@classmethod區(qū)別@staticmethod:靜態(tài)方法
@classmethod:類方法
一般來說,要使用某個類的方法,需要先實(shí)例化一個對象再調(diào)用方法。
而使用@staticmethod或@classmethod,就可以不需要實(shí)例化,直接通過類名就可以實(shí)現(xiàn)調(diào)用
使用:直接類名.方法名()來調(diào)用。@staticmethod和@classmethod都可以直接類名.方法名()來調(diào)用,
@staticmethod不需要表示自身對象的self和自身類的cls參數(shù)(這兩個參數(shù)都不需要添加),就跟使用函數(shù)一樣。
使用:直接類名.屬性名或直接類名.方法名。
@classmethod也不需要self參數(shù),但第一個參數(shù)需要是表示自身類的cls參數(shù)。
使用:直接類名.屬性名或直接類名.方法名。
兩者定義的裝飾器調(diào)用方法一樣,但是@classmethod裝飾器定義的類方法需要傳入類參數(shù)cls。
@staticmethod中要調(diào)用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
而@classmethod有cls參數(shù),可以來調(diào)用類的屬性,類的方法,實(shí)例化對象等,避免硬編碼更靈活。
2、@staticmethod和@classmethod使用示例代碼class A(object): def foo(self, x): print 'executing foo(%s, %s)' % (self, x) @classmethod def class_foo(cls, x): print 'executing class_foo(%s, %s)' % (cls, x) @staticmethod def static_foo(x): print 'executing static_foo(%s)' % x a = A()#通過實(shí)例調(diào)用方法,對象實(shí)例a作為第一個參數(shù)隱式傳遞。a.foo (1)# executing foo(<__main__.A object at 0xb7dbef0c>,1)#對于類方法,對象實(shí)例的類將隱式地作為第一個參數(shù)而不是傳遞selfa.class_foo(1)# executing class_foo(<class ’__main__.A’>,1)#使用這個類調(diào)用class_fooA.class_foo(1)# executing class_foo(<class ’__main__.A’>,1)#對于staticmethods,self(對象實(shí)例)和cls(類)都不會作為第一個參數(shù)隱式傳遞。它們的行為類似普通函數(shù),除了你可以從實(shí)例或類中調(diào)用它們a.static_foo(1)# executing static_foo(1)A.static_foo(’hi’)# executing static_foo(hi)print(a.foo)# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>print(a.class_foo)# <bound method type.class_foo of <class ’__main__.A’>>print(a.static_foo)# <function static_foo at 0xb7d479cc>print(a.static_foo)# <function static_foo at 0xb7d479cc>
總結(jié)一下彼此的調(diào)用區(qū)別:
到此這篇關(guān)于詳解Python中@staticmethod和@classmethod區(qū)別及使用示例代碼的文章就介紹到這了,更多相關(guān)Python @staticmethod和@classmethod內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 《CSS3實(shí)戰(zhàn)》筆記--漸變設(shè)計(jì)(一)2. 利用CSS制作3D動畫3. CSS3實(shí)現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效4. 測試模式 - XSL教程 - 55. 存儲于xml中需要的HTML轉(zhuǎn)義代碼6. HTML5 Canvas繪制圖形從入門到精通7. 用xslt+css讓RSS顯示的跟網(wǎng)頁一樣漂亮8. 讀大數(shù)據(jù)量的XML文件的讀取問題9. html5手機(jī)觸屏touch事件介紹10. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例
