4 ms·
Isn’t the double underscores __name would makes the method private?
by thangngoc89 2y ago
Isn’t the double underscores __name would makes the method private?
- zbentley 2y agoNo, that trick merely renames ("mangles") the method name: https://docs.python.org/3/reference/expressions.html#atom-identifiers https://docs.python.org/3/reference/expressions.html#atom-id... This is very rarely used to try to achieve privacy in practice, not least because it's extremely easy to get around.
- ajmurmann 2y agoSure it's only mangled. I'm Ruby you can also still call private methods via .send(:method_name). IMO the goal of declaring something private is to make clear what you consider part of your object's public API and it's safe for others to call. It's mainly to protect callers from shooting themselves in the foot. Private provides no security. Your consumer will know better the actual situation they are in and if it's worthwhile taking the risk that your API might break them in the future or to write additional tests since they are doing something you as the author advise against. Of course it can also help enforce good design within your project. IMO it should be easy to bypass private constraints when a user makes that educated choice
- lbhdc 2y agoThe names get mangled, but are still accessible. class Foo: __bar = 1 f = Foo() assert(f._Foo_bar == 1)