python笔记: staticmethod classmethod
生活随笔
收集整理的這篇文章主要介紹了
python笔记: staticmethod classmethod
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 前言
一般來說,如果我們要使用類中的方法,一般是實例化類中的對象,然后通過示例來調用函數,比如:
class myClass(object):def __init__(self,x):self.x=xdef printx(self):print(self.x)c=myClass(4) c.printx() # 4這時候,如果我們不實例化對象,直接用類名來調用函數,是不行的
myClass.printx()''' TypeError Traceback (most recent call last) <ipython-input-61-249ab211dc29> in <module> ----> 1 myClass.printx()TypeError: printx() missing 1 required positional argument: 'self' '''2 classmethod
????????類方法與類一起使用,因為它的參數始終是類本身。(實例的參數是看不到的)
? ? ? ? 但是,如果我們希望同時與類交互呢?我們可以使用@classmethod裝飾器來創建類方法
class myClass(object):x=1def __init__(self):self.x=x@classmethoddef printx(class_obj):print(class_obj.x)c=myClass() c.printx() #1 myClass.printx() #1????????這樣的好處是: 不管這個方式是從實例調用還是從類調用,它都用第一個參數把類傳遞過來.
3 staticmethod
????????有一些跟類有關系的功能,但在運行時又不需要實例和類參與。在這種情況下??梢杂玫届o態方法
????????靜態方法對類一無所知,只處理參數。
class myClass(object):def __init__(self,x):self.x=x@staticmethoddef printx():print('hello')c=myClass(1) c.printx() #hellomyClass(1).printx() #hello總結
以上是生活随笔為你收集整理的python笔记: staticmethod classmethod的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch笔记:torch.nn.G
- 下一篇: pytorch 笔记: 扩展torch.