一開(kāi)始我也是很蒙的,現(xiàn)在把自己的代碼及截圖給到大家馋辈,慢慢悟吧抚芦,去思考了才會(huì)更深刻,才會(huì)有自己的理解:
#繼承
class Father(object):
? ? f = 1
? ? def __init__(self, age):
? ? ? ? self.age=age
? ? ? ? print ( "Father——age: %d" %( self.age) )
? ? def getAge(self):
? ? ? ? print('Father------%d'%self.age)
? ? ? ? print(id(self))
class Son(Father):
#? ? f=2
? ? def __init__(self, age):
? ? ? ? print ( "son------hello world" )
? ? ? ? super().__init__(age)#使用super調(diào)用父類的方法
? ? ? ? self.age =? age
? ? def getAge(self):
? ? ? ? Father.getAge(self)#使用類名直接調(diào)用父類的方法迈螟,注意叉抡,這個(gè)時(shí)候就要傳入self參數(shù),不然報(bào)錯(cuò)self就是指向當(dāng)前的實(shí)例答毫!
? ? ? ? print('son------get age!')
? ? ? ? print(id(self))
son=Son(18)
son.getAge()
class Father():
? ? def __private(self):
? ? ? ? print("父類的私有函數(shù)private")
? ? def _protected(self):
? ? ? ? print("父類的受保護(hù)函數(shù)protected")
? ? def public(self):
? ? ? ? print("父類的公有函數(shù)public")
? ? ? ? self.__private()
? ? ? ? self._protected()
class Son(Father):
? ? __son='private_son'
? ? _son='protectes_son2'
? ? def __private(self):
? ? ? ? print("子類的重載私有函數(shù)private")
? ? def _protected(self):
? ? ? ? print("子類的重載受保護(hù)protected")
? ? def prit(self):
? ? ? ? print(self.__son)
s = Son()
s.public()
# 單下劃線的函數(shù)或?qū)傩匀烀瘢陬惖亩x中可以調(diào)用和訪問(wèn),類的實(shí)例也可以直接訪問(wèn)洗搂,子類也可以訪問(wèn)消返;s._protected()可以訪問(wèn)
# 雙下劃線的函數(shù)或?qū)傩裕陬惖亩x中可以調(diào)用和訪問(wèn)蚕脏,類的實(shí)例不可以直接訪問(wèn)侦副,子類不可以訪問(wèn)。s.__private()報(bào)錯(cuò)