python類變量的分類和調用方式


#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 父類
class JustCounter:
    '''
    類變量:類變量在整個實例化的對象中是公用的。類變量定義在類中且在函數體之外。類型:私有變量、保護變量、公開變量的調用方式。
    私有變量:兩個下划線開頭,聲明該屬性為私有,不能在類的外部或子類中被使用或直接訪問。在類內部的方法中使用時 self.__private
    保護變量:一個下划線開頭,聲明該屬性為protected。即保護類型只能允許其本身與子類進行訪問。在類內部的方法中使用時 self._private
    公開變量:
    '''
    __secretCount = 0  # 私有變量,只能在本類中調用self.__secretCount, 如果是其他地方調用:實例名._父類類名__secretCount
    # 保護變量 和 公開變量在類、子類、外部的調用方式相同。
    _protectCount = 0    # 保護變量
    publicCount = 0  # 公開變量
    def count(self):
        self.__secretCount += 1 # 在本類中調用私有變量
        self._protectCount += 2 # 在本類中調用保護變量
        self.publicCount += 3 # 在本類中調用公開變量
        print(self.__secretCount)
    def printout(self):
        print('私有變量:'+str(self.__secretCount))
        print('保護變量:'+str(self._protectCount))
        print('公開變量:'+str(self.publicCount))


# JustCounter的子類
class Child(JustCounter):
    def __init__(self):
        super().__init__()
    # 重寫父類方法
    def count(self):
        self._JustCounter__secretCount += 10 # 在子類中調用私有變量
        self._protectCount += 20 # 在子類中調用保護變量
        self.publicCount += 30 # 在子類中調用公開變量

        
child = Child()
child.count()
child.printout()
# 在類外部調用私有變量
print(str(child._JustCounter__secretCount))
print(str(child._protectCount))
print(str(child.publicCount))

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM