python无私有成员变量

本文通过实例演示了Python中如何定义私有属性以及如何从外部访问这些私有属性。介绍了Python解释器如何处理私有属性名,使得它们不易被直接访问,并展示了正确的访问方式。

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

python解释器将__init__函数里的__z变量转成 _classname__z了,明白规则后外部依然可以通过实力对象来访问。

In [1]: class aa:
   ...:     def __init__(self):
   ...:         self.x = 10
   ...:         self.y = 11
   ...:         self.__z = 12
   ...:     

In [2]: a = aa()

In [3]: print a.x
10

In [4]: print a.y
11

In [5]: print a.__z
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a90abb2fd47d> in <module>()
----> 1 print a.__z

AttributeError: aa instance has no attribute '__z'

In [6]: dir(a)
Out[6]: ['__doc__', '__init__', '__module__', '_aa__z', 'x', 'y']

In [7]: print _aa.__z
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-b2d0b9a63937> in <module>()
----> 1 print _aa.__z

NameError: name '_aa' is not defined

In [8]: print _aa__z
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-80bb4dde0a55> in <module>()
----> 1 print _aa__z

NameError: name '_aa__z' is not defined

In [9]: print a._aa__z
12

In [10]: a.__z = 14

In [11]: dir(a)
Out[11]: ['__doc__', '__init__', '__module__', '__z', '_aa__z', 'x', 'y']

In [12]: print a._aa__z
12





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值