python中的类方法和静态方法
類可以有類屬性,也可以有類方法,類方法主要是對類屬性的封裝。是類對象所擁有的方法,需要用修飾器@classmethod來標識其為類方法,對于類方法,第一個參數必須是類對象,一般以cls作為第一個參數(當然可以用其他名稱的變量作為其第一個參數,但是大部分人都習慣以'cls'作為第一個參數的名字,就最好用'cls'了),能夠通過實例對象和類對象去訪問。
?
類方法:
| class People(object): ? ??? #類屬性 ??? __country = 'china' ? ??? def __init__(self): ??????? self.name = "Edward" ? ??? #類方法,用classmethod來進行修飾 ??? @classmethod ??? def getCountry(cls): ??????? return cls.__country ? ??? # 類方法,用classmethod來進行修飾 ??? @classmethod ??? def setCountry(cls,country): ??????? cls.__country = country ? ??? #類方法不可使用實例屬性 ??? #類方法只能訪問類屬性 ??? #@classmethod ??? #def showPerson(cls): ??? #??? print(name) ? p = People() print(p.getCountry())??? #可以用過實例對象引用 print(People.getCountry())??? #可以通過類對象引用 print("----------------") p.setCountry("USA") print(p.getCountry())??? #可以用過實例對象引用 print(People.getCountry())??? #可以通過類對象引用 ? #p.showPerson() |
?
靜態方法:
需要通過修飾器@staticmethod來進行修飾,靜態方法不需要多定義參數.
| class People(object): ??? country = 'china' ? ??? @staticmethod ??? #靜態方法 ??? def getCountry(): ??????? return People.country ? #靜態方法不可訪問實例屬性 #靜態方法可以訪問類屬性 #通過對象可以訪問靜態方法 #通過類也可訪問靜態方法 print(People.getCountry()) person = People() print(person.getCountry()) |
?
總結:
|
總結
以上是生活随笔為你收集整理的python中的类方法和静态方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js固定表格行列_纯前端表格控件Spre
- 下一篇: Python 20 秒画完小猪佩奇“社会