python类变量

# 父类

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))

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值