Python 类中的数据隐藏是如何工作的?
数据隐藏
在 Python 中,我们在属性名称之前使用双下划线使其无法访问/私有或隐藏它们。
下面的代码展示了变量 __hiddenVar 如何隐藏。
示例
class MyClass: __hiddenVar = 0 def add(self, increment): self.__hiddenVar += increment print (self.__hiddenVar) myObject = MyClass() myObject.add(3) myObject.add (8) print (myObject.__hiddenVar)
输出
3 Traceback (most recent call last): 11 File "C:/Users/TutorialsPoint1/~_1.py", line 12, in <module> print (myObject.__hiddenVar) AttributeError: MyClass instance has no attribute '__hiddenVar'
在上面的程序中,我们尝试使用对象在类之外访问隐藏变量,并且它抛出了一个异常。
我们可以使用以下特殊语法访问隐藏属性的值 -
示例
class MyClass: __hiddenVar = 12 def add(self, increment): self.__hiddenVar += increment print (self.__hiddenVar) myObject = MyClass() myObject.add(3) myObject.add (8) print (myObject._MyClass__hiddenVar)
输出
15 23 23
私有方法可以从其类外部访问,但不像普通情况那样容易。在 Python 中,没有任何东西是真正私有的;在内部,私有方法和属性的名称会即时混乱和取消混乱,让它们无法通过给定名称访问。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP