Python中定义“私有”成员变量和成员函数

本文详细介绍了Python中如何通过下划线前缀来表示私有变量,并解释了namemangling技术如何使得私有变量不可从外部直接访问。通过示例代码演示了如何在类的内部和外部访问私有变量,以及在调试中的应用。

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

参考连接:http://docs.python.org/2/tutorial/classes.html    http://www.pythonclub.org/python-class/private    http://blog.youkuaiyun.com/mafuli007/article/details/7777641


在学习Python的过程中发下,它把类(class)中所有的成员函数和成员变量都看做是"Public"的,作为C++出身的程序员们可能就不习惯了。

Python的官方教程中如是说:““Private” instance variables that cannot be accessed except from inside an object don’t exist in Python.”。也就是说,在Python中我们不能够像C++或者Java那样有专门的private和public关键字来指定某些成员是公有的,哪些成员是私有的。

然而,Python教程中又说了:“However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.”。

OK,原来在Python中大家都是通过在一个变量或者函数之前加上下划线来表示私有变量的,例如__spam(这里是两个下划线)就是私有的。

同时,Python为了保证不能再class之外访问该变量,“Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.”,意思就是说,Python会在类的内部自动的把你定义的__spam变量的名字替换成为 _classname__spam(注意,classname前面是一个下划线,spam前是两个下划线),Python把这种技术叫做“name mangling”。因此,用户在外部访问__spam的时候就会提示找不到相应的变量。

下面给出一段简单的代码:


#!/usr/bin/python
#Filename: classPrivate.py

class testPrivate:
	def __init__(self):
		self.__data = []

	def add(self,item):
		self.__data.append(item)
	def printData(self):
		print (self.__data)

t = testPrivate()
t.add('dancingrain')
t.add('hello')
t.printData()
print(t.__data)

输出结果是:



可以看出,当执行print(t.__data)的时候提示我们没有该属性,OK!这就是我们想要的结果。


但是,这并不是意味着我们真的就不能够从外部访问这个变量了,上面说Python在类的内部用_classname__spam替换了__spam,

因此,我们可以在类的外面使用_classname__spam来访问__spam。看看下面的代码:


#!/usr/bin/python
#Filename: classPrivate.py

class testPrivate:
	def __init__(self):
		self.__data = []

	def add(self,item):
		self.__data.append(item)
	def printData(self):
		print (self.__data)

t = testPrivate()
t.add('dancingrain')
t.add('hello')
t.printData()
print(t._testPrivate__data)

结果是:




OK,我们在外面也能够访问该“私有”变量了,

这一点在调试中是比较有用的!




### Python私有属性与私有方法的区别 #### 定义上的差异 在 Python 编程语言中,私有属性私有方法都是为了实现封装这一重要概念而存在。这些成员旨在仅限于类内部使用,防止外部直接访问从而保护对象的状态[^2]。 对于私有属性而言,在定义时通常会在名称前加上两个下划线`__`,这使得该属性成为所谓的“伪私有”,即它会被名字改写(name mangling),增加了从外界直接引用此属性的难度[^3]。 而对于私有方法,则同样遵循上述命名约定——以双下划线开头。这类方法也受到相同的名字改写的处理,并且主要用于支持类的功能而不对外公开接口[^1]。 #### 访问权限的不同表现形式 当涉及到实际操作层面时,虽然两者都难以被实例直接获取或调用,但是具体行为还是有所区别的: - **私有属性**: 主要用来保存不应暴露给用户的敏感数据或其他不需要让用户知道的信息。即使是在同一个模块内创建的对象也不能轻易改变其值除非通过特定的方法间接完成。 - **私有方法**: 更多地是为了辅助其他公共函数完成某些逻辑运算或是提供一些工具性的功能。由于它们不是API的一部分所以不应该也不必让使用者知晓具体的实现细节。 ```python class ExampleClass: def __init__(self): self.__private_attr = "This is a private attribute" # 私有属性 def public_method(self): print("Calling the private method:") self.__private_method() # 调用私有方法 def __private_method(self): # 私有方法 print(f"{self.__private_attr} from inside class.") example_instance = ExampleClass() try: example_instance.public_method() except AttributeError as e: print(e) print("\nAttempting to access private members directly:") try: print(example_instance.__private_attr) # 尝试直接访问私有属性会失败 except AttributeError as e: print(e) try: example_instance.__private_method() # 尝试直接调用私有方法也会失败 except AttributeError as e: print(e) ``` 这段代码展示了如何在一个类里声明并尝试访问私有属性以及私有方法的情况。可以看到,尽管工作方法能够正常地读取到对象内的私有成分,但从外部却无法做到这一点。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值