保護變量、私有變量、私有方法介紹:python
_xxx: 單下劃線開頭叫保護變量,意思是隻有類對象和子類對象本身能訪問到這些變量,此變量不能經過from XXX import xxx 導入;
__xxx : 雙下劃線開頭叫私有成員,只容許類自己訪問,連子類對象也不能訪問到這個數據。
__xxx__ : 先後均有一個「雙下劃線」,系統定義名字, 表明python裏特殊方法專用的標識,如 __init__()表明類的構造函數。
代碼示例:
class Pub(object): #定義類的正常變量、保護變量、私有變量 var1 = 'Hello' _var2 = 'yes' __var3 = 'haha' #表明類的構造函數 def __init__(self): self._a = 123 self.__b = 456 self.c = 789 def show_a_var(self): return self._a def show_b_var(self): return self.__b def show_var2(self): return self._var2 def show_var3(self): return self.__var3 #定義私有方法 def __privatemethod(self): print('這是私有方法') class Foo(Pub): pass # 類的實例化對象 sl = Pub() #第一:訪問正常變量 print(sl.c) # 789 print(sl.var1) #第二:訪問保護變量 print(sl._a) # 123 print(sl._var2) #yes #第三:訪問私有變量:實例._類名__變量名 print(sl._Pub__var3) # haha print(sl._Pub__b) #456 # print(sl.__b) #錯誤的寫法 #第四:訪問正常類方法 print(sl.show_a_var()) #123 print(sl.show_b_var()) #456 間接去訪問,獲得self.__b print(sl.show_var2()) #yes print(sl.show_var3()) #haha 間接去訪問,獲得self.__var3 #第五:訪問私有方法: 實例._類名__方法名() sl._Pub__privatemethod() #結果:這是私有方法 #子類的實例化對象 s2=Foo() print(s2.show_a_var()) #123 print(s2.show_b_var()) #456 print(s2.show_var2()) #ye3 print(s2.show_var3()) #haha
私有變量、私有方法應用:函數
class people(): __place = "nanjing" _age1 = 20 def __init__(self, name): self.name = name def __sayhello(self): print("%s say hello" % self.name) class teacher(people): pass t1 = teacher("cmz") print(t1._people__place) # 訪問私有變量 t1._people__sayhello() # 訪問私有方法 結果是 nanjing cmz say hello python私有屬性和方法案例
單下劃線應用:
class people(): __place = "nanjing" _age = 20 def __init__(self, name): self.name = name def _test(self): print("from people test") def __sayhello(self): print("%s say hello" % self.name) class teacher(people): pass print(people.__dict__) #<class '__main__.people'> t1 = teacher("cmz") print(t1) #<__main__.teacher object at 0x029026F0> #獲得年齡2中方式 #方式一 print(t1._age) #20 #方式二 # print(people._age) #調用test函數2中方式 #方式一 t1._test() #方式二 people._test(t1) #調用私有方法 t1._people__sayhello() #cmz say hello '''結果 {'__module__': '__main__', '_people__place': 'nanjing', '_age': 20, '__init__': <function people.__init__ at 0x0081B5D0>, '_test': <function people._test at 0x0081B4F8>, '_people__sayhello': <function people.__sayhello at 0x050674F8>, '__dict__': <attribute '__dict__' of 'people' objects>, '__weakref__': <attribute '__weakref__' of 'people' objects>, '__doc__': None} <__main__.teacher object at 0x00359390> 20 from people test from people test cmz say hello '''
雙下劃線應用:
class people(): __place = "nanjing" _age = 20 def __init__(self, name): self.name = name def __sayhello(self): print("%s say hello" % self.name) class teacher(people): pass t1 = teacher("cmz") print(t1._people__place) t1._people__sayhello() 結果是 nanjing cmz say hello