34.Python进阶_类的私有属性

类里面定义的属性叫类属性,那么类属性有两种,分为:共有属性和私有属性
Python并没有真正的私有化支持,但可用下划线得到伪私有
私有属性定义:

  • 单下滑线开头:_attr protected
  • 双下划线开头:__attr private

单下滑线私有属性:外部可以直接访问;
表示的是protected(受保护的) 类型的变量,只能靠允许其本身与子类进行访问。,如:当使用“from M import” 时,不会将一个下划线开头的对象引入。

双下滑线私有属性:外部不可直接访问,被改名了,所以在外部无法访问,改成了__类名__attr2

只能在类内部中访问,类外部包括子类访问则报错

class Hero():
    attr = 1
    _attr1 = 2
    __attr2 = 3
    
print(Hero.attr)
print(Hero._attr1)
print(Hero.__attr2)

运行结果:

1
2
Traceback (most recent call last):
  File "C:/workspace/pythonTest/pythonDemo/siyou.py", line 8, in <module>
    print(Hero.__attr2)
AttributeError: type object 'Hero' has no attribute '__attr2'

受保护类型子类可访问, 私有属性子类同样不可访问:

class Hero():
    attr = 1
    _attr1 = 2
    __attr2 = 3

    def fun(self):  #类内部访问
        print(self.attr)
        print(self._attr1)
        print(self.__attr2)

class Dog(Hero):
    def fun(self):  #继承的子类访问
       print(self.attr)
       print(self._attr1)
       print(self.__attr2)

h=Hero() 
h.fun()


d = Dog()
d.fun()

运行结果:

1
2
3
1
2
Traceback (most recent call last):
  File "C:/workspace/pythonTest/pythonDemo/siyou.py", line 20, in <module>
    d.fun()
  File "C:/workspace/pythonTest/pythonDemo/siyou.py", line 15, in fun
    print(self.__attr2)
AttributeError: 'Dog' object has no attribute '_Dog__attr2'
小结:
  • 单下划线私有属性(protected): 类内部可访问,子类可访问,导入后不可访问;
  • 双下划线私有属性(private):类内部可访问,子类及类外都不可访问;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值