#!/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))