Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are Python's 'private' methods not actually private?
    text
    copied!<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>>>> 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!! </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>>>> class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... >>> obj = MyClass() </code></pre> <p>What I did there is 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>>>> obj.myPublicMethod() public method </code></pre> <p>Next, I try and call its private method.</p> <pre><code>>>> obj.__myPrivateMethod() Traceback (most recent call last): File "", line 1, in 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 <em>dir()</em> on the object reveals a new magical method that python creates magically for all of your 'private' methods.</p> <pre><code>>>> 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>>>> 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>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload