相关疑难解决方法(0)

为什么Python的"私有"方法实际上不是私有的?

Python使我们能够通过在名称前加上双下划线来在类中创建"私有"方法和变量,如下所示:__myPrivateMethod().那么,如何解释这一点呢

>>> class MyClass:
...     def myPublicMethod(self):
...             print 'public method'
...     def __myPrivateMethod(self):
...             print 'this is private!!'
... 
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?!

我会对那些没有那么做的人解释一下.

>>> class MyClass:
...     def myPublicMethod(self):
...             print 'public method'
...     def __myPrivateMethod(self):
...             print 'this is private!!'
... 
>>> obj = MyClass()
Run Code Online (Sandbox Code Playgroud)

我在那里做的是使用公共方法和私有方法创建一个类并实例化它.

接下来,我称之为公共方法.

>>> obj.myPublicMethod() …
Run Code Online (Sandbox Code Playgroud)

python encapsulation information-hiding python-2.7

632
推荐指数
11
解决办法
41万
查看次数