Python類中的單下劃線和雙下劃線的區別
阿新 • • 發佈:2018-11-11
#"單下劃線" 開始的成員變數叫做保護變數,意思是隻有類物件和子類物件自己能訪問到這些變數;
#"雙下劃線" 開始的是私有成員,意思是隻有類物件自己能訪問,連子類物件也不能訪問到
#-*-coding:utf8-*- class father(): def __init__(self): print("father object") def __add(self): print("father add") def _main(self): self.__add() print("father man") class son(father): def __add(self): print("son add") test=son() test._main()
實驗結果:
D:\Python36\python.exe D:/Users/liusen/PycharmProjects/coding_work/object_test/test_object.py
father object
father add
father man
Process finished with exit code 0
#-*-coding:utf8-*- class father(): def __init__(self): print("father object") def _add(self): print("father add") def _main(self): self._add() print("father man") class son(father): def _add(self): print("son add") test=son() test._main()
實驗結果:
D:\Python36\python.exe D:/Users/liusen/PycharmProjects/coding_work/object_test/test_object.py
father object
son add
father man
Process finished with exit code 0
#-*-coding:utf8-*- class father(): def __init__(self): print("father object") def add(self): print("father add") def _main(self): self.add() print("father man") class son(father): def add(self): print("son add") test=son() test._main()
實驗結果:
D:\Python36\python.exe D:/Users/liusen/PycharmProjects/coding_work/object_test/test_object.py
father object
son add
father man
Process finished with exit code 0