python基礎2-靜態方法和類方法
阿新 • • 發佈:2017-05-17
變量 img 靜態 訪問 func title 改變 參數 code
1. 類方法
是類對象所擁有的方法,需要用修飾器@classmethod
來標識其為類方法,對於類方法,第一個參數必須是類對象,一般以cls
作為第一個參數(當然可以用其他名稱的變量作為其第一個參數,但是大部分人都習慣以‘cls‘作為第一個參數的名字,就最好用‘cls‘了),能夠通過實例對象和類對象去訪問。
class people:
country = ‘china‘
#類方法,用classmethod來進行修飾
@classmethod
def getCountry(cls):
return cls.country
p = people()
print p.getCountry() #可以用過實例對象引用
print people.getCountry() #可以通過類對象引用
類方法還有一個用途就是可以對類屬性進行修改:
class people:
country = ‘china‘
#類方法,用classmethod來進行修飾
@classmethod
def getCountry(cls):
return cls.country
@classmethod
def setCountry(cls,country):
cls.country = country
p = people()
print p.getCountry() #可以用過實例對象引用
print people.getCountry() #可以通過類對象引用
p.setCountry(‘japan‘)
print p.getCountry()
print people.getCountry()
結果顯示在用類方法對類屬性修改之後,通過類對象和實例對象訪問都發生了改變
2. 靜態方法
需要通過修飾器@staticmethod
來進行修飾,靜態方法不需要多定義參數
class people:
country = ‘china‘
@staticmethod
#靜態方法
def getCountry():
return people.country
print people.getCountry()
總結
從類方法和實例方法以及靜態方法的定義形式就可以看出來,類方法的第一個參數是類對象cls,那麽通過cls引用的必定是類對象的屬性和方法;而實例方法的第一個參數是實例對象self,那麽通過self引用的可能是類屬性、也有可能是實例屬性(這個需要具體分析),不過在存在相同名稱的類屬性和實例屬性的情況下,實例屬性優先級更高。靜態方法中不需要額外定義參數,因此在靜態方法中引用類屬性的話,必須通過類對象來引用
python基礎2-靜態方法和類方法