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

为什么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!!

怎么回事?!

我给那些不太明白的人解释一下。

>>> 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'

这里一切都很好,我们不能称之为。事实上,它是‘私人的’。其实不是。跑迪尔()在对象上,揭示了python为您的所有“私有”方法神奇地创建的一种新的神奇方法。

>>> dir(obj)['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']

此新方法的名称始终是下划线,后面是类名,后面是方法名。

>>> obj._MyClass__myPrivateMethod()this is private!!

封装就这么多了,嗯?

在任何情况下,我都听说Python不支持封装,那么为什么还要尝试呢?什么给予?


慕桂英546537
浏览 994回答 3
3回答

森栏

名称置乱用于确保子类不会意外地覆盖其超类的私有方法和属性。它的设计并不是为了防止故意从外部进入。例如:>>> class Foo(object):...     def __init__(self):...         self.__baz = 42...     def foo(self):...         print self.__baz...     >>> class Bar(Foo):...     def __init__(self):...         super(Bar, self).__init__()...         self.__baz = 21...     def bar(self):...         print self.__baz...>>> x = Bar()>>> x.foo()42>>> x.bar()21>>> print x.__dict__{'_Bar__baz': 21, '_Foo__baz': 42}当然,如果两个不同的类有相同的名称,它就会分解。

qq_笑_17

私有函数示例import reimport inspectclass MyClass :     def __init__(self) :         pass     def private_function ( self ) :         try :             function_call = inspect.stack()[1][4][0].strip()             # See if the function_call has "self." in the begining             matched = re.match( '^self\.', function_call )             if not matched :                 print 'This is Private Function, Go Away'                 return         except :             print 'This is Private Function, Go Away'             return         # This is the real Function, only accessible inside class #         print 'Hey, Welcome in to function'     def public_function ( self ) :         # i can call private function from inside the class         self.private_function()### End ###

肥皂起泡泡

当我第一次从Java到Python时痛恨这,这个。把我吓死了。今天也许只有一件事我最爱关于Python。我喜欢在一个平台上,人们互相信任,不觉得他们需要在代码周围建造无法穿透的墙。在强封装的语言中,如果一个API有一个bug,并且您已经知道出了什么问题,那么您可能仍然无法绕过它,因为所需的方法是私有的。在Python中,态度是:“当然”。如果你认为你了解情况,也许你甚至读过,那我们只能说“祝你好运!”请记住,封装与“安全性”或让孩子远离草坪的关系并不弱。这只是另一种模式,应该用来使代码库更容易理解。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python