<p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>&gt;&gt;&gt;&gt; class MyClass:
...     def myPublicMethod(self):
...             print 'public method'
...     def __myPrivateMethod(self):
...             print 'this is private!!'
...
&gt;&gt;&gt; obj = MyClass()

&gt;&gt;&gt; obj.myPublicMethod()
public method

&gt;&gt;&gt; obj.__myPrivateMethod()
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
AttributeError: MyClass instance has no attribute '__myPrivateMethod'

&gt;&gt;&gt; dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']

&gt;&gt;&gt; obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>&gt;&gt;&gt; class MyClass:
...     def myPublicMethod(self):
...             print 'public method'
...     def __myPrivateMethod(self):
...             print 'this is private!!'
...
&gt;&gt;&gt; obj = MyClass()
</code></pre>
<p>I create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>&gt;&gt;&gt; obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>&gt;&gt;&gt; obj.__myPrivateMethod()
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <code>dir()</code> on the object reveals a new magical method that Python creates magically for all of your 'private' methods.</p>
<pre><code>&gt;&gt;&gt; dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>&gt;&gt;&gt; obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>

[{'answer_id': 70555, 'author': 'xsl', 'author_id': 11387, 'author_profile': 'https://Stackoverflow.com/users/11387', 'pm_score': 7, 'selected': False, 'text': '<p>From <em><a href="http://www.faqs.org/docs/diveintopython/fileinfo_private.html" rel="noreferrer">Dive Into Python, 3.9. Private functions</a></em>:</p>\n<blockquote>\n<p>Strictly speaking, private methods are\naccessible outside their class, just\nnot easily accessible. Nothing in\nPython is truly private; internally,\nthe names of private methods and\nattributes are mangled and unmangled\non the fly to make them seem\ninaccessible by their given names. You\ncan access the __parse method of the\nMP3FileInfo class by the name\n_MP3FileInfo__parse. Acknowledge that this is interesting, then promise to\nnever, ever do it in real code.\nPrivate methods are private for a\nreason, but like many other things in\nPython, their privateness is\nultimately a matter of convention, not\nforce.</p>\n</blockquote>\n'}, {'answer_id': 70562, 'author': 'Maximilian', 'author_id': 1733, 'author_profile': 'https://Stackoverflow.com/users/1733', 'pm_score': 5, 'selected': False, 'text': "<p>It's not like you absolutely can't get around privateness of members in any language (pointer arithmetics in C++ and reflections in .NET/Java).</p>\n<p>The point is that you get an error if you try to call the private method by accident. But if you want to shoot yourself in the foot, go ahead and do it.</p>\n<p>You don't try to secure your stuff by OO-encapsulation, do you?</p>\n"}, {'answer_id': 70583, 'author': 'ctcherry', 'author_id': 10322, 'author_profile': 'https://Stackoverflow.com/users/10322', 'pm_score': 4, 'selected': False, 'text': "<p>It's just one of those language design choices. On some level they are justified. They make it so you need to go pretty far out of your way to try and call the method, and if you really need it that badly, you must have a pretty good reason!</p>\n\n<p>Debugging hooks and testing come to mind as possible applications, used responsibly of course.</p>\n"}, {'answer_id': 70736, 'author': 'Tony Meyer', 'author_id': 4966, 'author_profile': 'https://Stackoverflow.com/users/4966', 'pm_score': 7, 'selected': False, 'text': '<p>The phrase commonly used is &quot;we\'re all consenting adults here&quot;.  By prepending a single underscore (don\'t expose) or double underscore (hide), you\'re telling the user of your class that you intend the member to be \'private\' in some way.  However, you\'re trusting everyone else to behave responsibly and respect that, unless they have a compelling reason not to (e.g., debuggers and code completion).</p>\n<p>If you truly must have something that is private, then you can implement it in an extension (e.g., in C for <a href="https://en.wikipedia.org/wiki/CPython" rel="noreferrer">CPython</a>).  In most cases, however, you simply learn the <a href="https://en.wiktionary.org/wiki/Pythonic#Adjective" rel="noreferrer">Pythonic</a> way of doing things.</p>\n'}, {'answer_id': 70900, 'author': 'Alya', 'author_id': 9464, 'author_profile': 'https://Stackoverflow.com/users/9464', 'pm_score': 10, 'selected': True, 'text': "<p>The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.</p>\n\n<p>For example:</p>\n\n<pre><code>&gt;&gt;&gt; class Foo(object):\n...     def __init__(self):\n...         self.__baz = 42\n...     def foo(self):\n...         print self.__baz\n...     \n&gt;&gt;&gt; class Bar(Foo):\n...     def __init__(self):\n...         super(Bar, self).__init__()\n...         self.__baz = 21\n...     def bar(self):\n...         print self.__baz\n...\n&gt;&gt;&gt; x = Bar()\n&gt;&gt;&gt; x.foo()\n42\n&gt;&gt;&gt; x.bar()\n21\n&gt;&gt;&gt; print x.__dict__\n{'_Bar__baz': 21, '_Foo__baz': 42}\n</code></pre>\n\n<p>Of course, it breaks down if two different classes have the same name.</p>\n"}, {'answer_id': 80000, 'author': 'Ross', 'author_id': 14794, 'author_profile': 'https://Stackoverflow.com/users/14794', 'pm_score': 4, 'selected': False, 'text': '<p>Similar behavior exists when module attribute names begin with a single underscore (e.g. _foo).</p>\n\n<p>Module attributes named as such will not be copied into an importing module when using the <code>from*</code> method, e.g.:</p>\n\n<pre><code>from bar import *\n</code></pre>\n\n<p>However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation.</p>\n'}, {'answer_id': 1949874, 'author': 'Thomas Ahle', 'author_id': 205521, 'author_profile': 'https://Stackoverflow.com/users/205521', 'pm_score': 8, 'selected': False, 'text': '<p>When I first came from Java to Python I <strong>hated</strong> this. It scared me to death.</p>\n\n<p>Today it might just be the one thing <strong>I love most</strong> about Python.</p>\n\n<p>I love being on a platform, where people trust each other and don\'t feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, if an API has a bug, and you have figured out what goes wrong, you may still be unable to work around it because the needed method is private. In Python the attitude is: "sure". If you think you understand the situation, perhaps you have even read it, then all we can say is "good luck!".</p>\n\n<p>Remember, encapsulation is not even weakly related to "security", or keeping the kids off the lawn. It is just another pattern that should be used to make a code base easier to understand.</p>\n'}, {'answer_id': 3147548, 'author': 'arun', 'author_id': 379816, 'author_profile': 'https://Stackoverflow.com/users/379816', 'pm_score': 8, 'selected': False, 'text': "<h3>Example of a private function</h3>\n<pre><code>import re\nimport inspect\n\nclass MyClass:\n\n    def __init__(self):\n        pass\n\n    def private_function(self):\n        try:\n            function_call = inspect.stack()[1][4][0].strip()\n\n            # See if the function_call has &quot;self.&quot; in the beginning\n            matched = re.match( '^self\\.', function_call)\n            if not matched:\n                print 'This is a private function. Go away.'\n                return\n        except:\n            print 'This is a private function. Go away.'\n            return\n\n        # This is the real function, only accessible inside the class #\n        print 'Hey, welcome in to the function.'\n\n    def public_function(self):\n        # I can call a private function from inside the class\n        self.private_function()\n\n### End ###\n</code></pre>\n"}, {'answer_id': 39123423, 'author': 'Alberto', 'author_id': 1735667, 'author_profile': 'https://Stackoverflow.com/users/1735667', 'pm_score': 2, 'selected': False, 'text': '<p>With Python 3.4, this is the behaviour:</p>\n<pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; class Foo:\n        def __init__(self):\n                pass\n        def __privateMethod(self):\n                return 3\n        def invoke(self):\n                return self.__privateMethod()\n\n\n&gt;&gt;&gt; help(Foo)\nHelp on class Foo in module __main__:\n\nclass Foo(builtins.object)\n |  Methods defined here:\n |\n |  __init__(self)\n |\n |  invoke(self)\n |\n |  ----------------------------------------------------------------------\n |  Data descriptors defined here:\n |\n |  __dict__\n |      dictionary for instance variables (if defined)\n |\n |  __weakref__\n |      list of weak references to the object (if defined)\n\n &gt;&gt;&gt; f = Foo()\n &gt;&gt;&gt; f.invoke()\n 3\n &gt;&gt;&gt; f.__privateMethod()\n Traceback (most recent call last):\n   File &quot;&lt;pyshell#47&gt;&quot;, line 1, in &lt;module&gt;\n     f.__privateMethod()\n AttributeError: \'Foo\' object has no attribute \'__privateMethod\'\n</code></pre>\n<p>From <em><a href="https://docs.python.org/3/tutorial/classes.html#tut-private" rel="nofollow noreferrer">9.6. Private Variables</a></em>:</p>\n<blockquote>\n<p>Note that the mangling rules are designed mostly to avoid accidents; <strong>it still is possible to access or modify a variable that is considered private.</strong> This can even be useful in special circumstances, such as in the debugger.</p>\n</blockquote>\n'}, {'answer_id': 50052800, 'author': 'Afshin Amiri', 'author_id': 6244155, 'author_profile': 'https://Stackoverflow.com/users/6244155', 'pm_score': 3, 'selected': False, 'text': '<p>The most important concern about private methods and attributes is to tell developers not to call it outside the class and this is encapsulation. One may misunderstand security from encapsulation. When one deliberately uses syntax like that (below) you mentioned, you do not want encapsulation.</p>\n<pre><code>obj._MyClass__myPrivateMethod()\n</code></pre>\n<p>I have migrated from C# and at first it was weird for me too but after a while I came to the idea that only the way that Python code designers think about OOP is different.</p>\n'}, {'answer_id': 54179468, 'author': 'user200783', 'author_id': 200783, 'author_profile': 'https://Stackoverflow.com/users/200783', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n<p>Why are Python's 'private' methods not actually private?</p>\n</blockquote>\n<p>As I understand it, they <em>can't</em> be private. How could privacy be enforced?</p>\n<p>The obvious answer is &quot;private members can only be accessed through <code>self</code>&quot;, but that wouldn't work - <code>self</code> is not special in Python. It is nothing more than a commonly-used name for the first parameter of a function.</p>\n"}, {'answer_id': 64985332, 'author': 'Moradnejad', 'author_id': 2419960, 'author_profile': 'https://Stackoverflow.com/users/2419960', 'pm_score': 4, 'selected': False, 'text': '<h1>Important note:</h1>\n<p>Any identifier of the form <code>__name</code> (at least two leading underscores, at most one trailing underscore) is publicly replaced with <code>_classname__name</code>, where <code>classname</code> is the current class name with a leading underscore(s) stripped.</p>\n<p><strong>Therefore, <code>__name</code> is not accessible directly, but can be accessed as<code>_classname__name</code>.</strong></p>\n<p>This does not mean that you can protect your private data as it is easily accessible by changing the name of the variable.</p>\n<h4>Source:</h4>\n<p>&quot;Private Variables&quot; section in official documentation: <a href="https://docs.python.org/3/tutorial/classes.html#tut-private" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/classes.html#tut-private</a></p>\n<h2>Example</h2>\n<pre class="lang-py prettyprint-override"><code>class Cat:\n    def __init__(self, name=\'unnamed\'):\n        self.name = name\n    def __print_my_name(self):\n        print(self.name)\n        \n        \ntom = Cat()\ntom.__print_my_name() #Error\ntom._Cat__print_my_name() #Prints name\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/70528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1943957/']