Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like so: *__myPrivateMethod()*. How, then, can one explain this
What's the deal?!
I'll explain this a little for those who didn't quite get that.
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
Next, I try and call its private method.
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't.
Running dir() on the object reveals a new magical method that python creates magically for all of your 'private' methods.
This new method's name is always an underscore, followed by the class name, followed by the method name.
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?
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.
For example:
Of course, it breaks down if two different classes have the same name.
Written by Vivek Soundrapandi
Published Date: {{ article.pub_date }}
View all posts by: Vivek Soundrapandi