Python 类中的数据隐藏如何工作?

pythonserver side programmingprogramming

数据隐藏

在 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, increase):
       self.__hiddenVar += increase
       print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject._MyClass__hiddenVar)

输出

15
23
23

私有方法可以从其类外部访问,但不像正常情况下那么容易。Python 中没有任何东西是真正私有的;在内部,私有方法和属性的名称会动态地被破坏和恢复,使其无法通过给定的名称访问。


相关文章


有用资源