静态方法和类方法
1. 類方法
是類對(duì)象所擁有的方法,需要用修飾器@classmethod來標(biāo)識(shí)其為類方法,對(duì)于類方法,第一個(gè)參數(shù)必須是類對(duì)象,一般以cls作為第一個(gè)參數(shù)(當(dāng)然可以用其他名稱的變量作為其第一個(gè)參數(shù),但是大部分人都習(xí)慣以'cls'作為第一個(gè)參數(shù)的名字,就最好用'cls'了),能夠通過實(shí)例對(duì)象和類對(duì)象去訪問。
class people:country = 'china'#類方法,用classmethod來進(jìn)行修飾@classmethoddef getCountry(cls):return cls.countryp = people() print p.getCountry() #可以用過實(shí)例對(duì)象引用 print people.getCountry() #可以通過類對(duì)象引用?類方法還有一個(gè)用途就是可以對(duì)類屬性進(jìn)行修改:
class people:country = 'china'#類方法,用classmethod來進(jìn)行修飾@classmethoddef getCountry(cls):return cls.country@classmethoddef setCountry(cls,country):cls.country = countryp = people() print p.getCountry() #可以用過實(shí)例對(duì)象引用 print people.getCountry() #可以通過類對(duì)象引用p.setCountry('japan') print p.getCountry() print people.getCountry()?運(yùn)行結(jié)果:
china china japan japan2. 靜態(tài)方法
需要通過修飾器@staticmethod來進(jìn)行修飾,靜態(tài)方法不需要多定義參數(shù)
class people:country = 'china'@staticmethod#靜態(tài)方法def getCountry():return people.countryprint people.getCountry()?
總結(jié)
從類方法和實(shí)例方法以及靜態(tài)方法的定義形式就可以看出來,類方法的第一個(gè)參數(shù)是類對(duì)象cls,那么通過cls引用的必定是類對(duì)象的屬性和方法;而實(shí)例方法的第一個(gè)參數(shù)是實(shí)例對(duì)象self,那么通過self引用的可能是類屬性、也有可能是實(shí)例屬性(這個(gè)需要具體分析),不過在存在相同名稱的類屬性和實(shí)例屬性的情況下,實(shí)例屬性優(yōu)先級(jí)更高。靜態(tài)方法中不需要額外定義參數(shù),因此在靜態(tài)方法中引用類屬性的話,必須通過類對(duì)象來引用
轉(zhuǎn)載于:https://www.cnblogs.com/loaderman/p/6561878.html
總結(jié)
- 上一篇: Java自学资料!你确定你真的理解_双亲
- 下一篇: JAVA的三大框架是什么?