【3.7】数据封装和私有属性

本文介绍了Python中如何使用双下划线实现私有属性,并通过示例解释了名称变更的过程及其实现机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 在Python中,实例属性如果以双下划线开头,那么这个属性就是一个私有属性

 1 class Test:
 2     def __init__(self, x):
 3         self.__x = x
 4 
 5     def the_print(self):
 6         print(self.__x)
 7 
 8 
 9 t = Test(1)
10 print(t.__x)
11 t.the_print()
Traceback (most recent call last):
  File "demo.py", line 14, in <module>
    print(t.__x)
AttributeError: 'Test' object has no attribute '__x'

  但是,Python实现这种私有属性的方法,仅仅是通过改变该变量的名称来达到的

 1 class Test:
 2     def __init__(self, x):
 3         self.__x = x
 4 
 5     def the_print(self):
 6         print(self.__x)
 7 
 8 
 9 t = Test(1)
10 print(t.__dir__())
11 print(t._Test__x)
12 t.the_print()
['_Test__x', '__module__', '__init__', 'the_print', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__',
'__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
1
1

  __x --> _Test__x

转载于:https://www.cnblogs.com/zydeboke/p/11238539.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值