通過class關(guān)鍵字定義自己的類,類里面的內(nèi)容都包含啥呢秒紧?
類的定義如下:class ? Person:
內(nèi)容呢绢陌?不要著急,請繼續(xù)往下看呀H刍帧F晖濉!P鹛省秤掌!
one.我們來了解一下變量吧,類內(nèi)部的變量有私有變量和公有變量,如下:
? ? ? ? ? ? ? ? ? __selfcounter =0# 私有變量
? ? ? ? ? ? ? ? ? publiccounter =0# 公開變量
two.構(gòu)造函數(shù),聽起來有沒有有點高大上了鹰霍,呵呵呵~~~
? ? ? ? ? ? ? ?def__init__(self,a,b):
? ? ? ? ? ? ? ? ? ? ? ?self.__selfcounter = a
? ? ? ? ? ? ? ? ? ? ? ?self.publiccounter = b
three.普通的公開方法闻鉴,例如:
? ? ? ? ? ? ? defcount(self):
? ? ? ? ? ? ? ? ? ? ? ?self.__selfcounter+=2
? ? ? ? ? ? ? ? ? ? ? ?self.publiccounter +=3
? ? ? ? ? ? ? ? ? ? ? printself.__selfcounter
four.protected方法,以供自己以及子類使用
? ? ? ? ? ? ? ? def_count2(self):
? ? ? ? ? ? ? ? ? ? ? printself.__selfcounter
five.私有方法茂洒,只能提供自己內(nèi)部使用
? ? ? ? ? ? ? ? ? ?def__count3(self):
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?print"私有方法輸出孟岛!"
over~~~~別期待了,類里面就這些玩意督勺,想找更多的你只能去度娘了哈哈哈哈
怎么實例化去調(diào)用呢渠羞,請看這里:
? ? ? ? ? ? ? ? #實例化類調(diào)用方法
? ? ? ? ? ? ? ? counter1 = Person(20,30)
? ? ? ? ? ? ? ? counter1.count()
? ? ? ? ? ? ? ? #實例化類調(diào)用變量
? ? ? ? ? ? ? ? counter2 = Person(50,50)
? ? ? ? ? ? ? ? ?counter2.publiccounter
類和類之間如同人之間是可以繼承的,就想你家娃繼承了你那么多優(yōu)點智哀,有木有很想知道Python怎么繼承的呢
classSubPerson(Person):# 定義Person的子類
那可以繼承多個嗎次询?當(dāng)然
classSubPerson(Person1,Person2):#繼承多個父類