Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Funnily enough, just starting your class method/variable name with __ does do magic things as a pseudo-keyword. Specifically, it mangles the name for callers outside of that class -- `self.__foo` would need to be accessed as `obj._ClassName__foo`. It's python's approach to having private methods, while remaining somewhat ideologically opposed to them existing.

This doesn't apply to the dunder methods, though. They're magically exempt from this magical mangling, so you could call them directly if you wanted. ¯\_(ツ)_/¯

> You don't think the Python way is worse?

They seem about equivalent? I don't see any real reason to pick one or the other, beyond personal preferences.



What's the use case for __foo -> _ClassName__foo? I've used python a bunch but never this feature, so I'm curious.


It prevents accidentally overriding the member in subclasses which can prevent private implementation details of parent classes from being accidentally interfered with by child classes.

As composition over inheritance becomes more idiomatic, there are probably less places where this matters, but as long as inheritance is used at all it can be useful.


It makes it nearly impossible to reference that attribute by accident. Basically, if class Foo defines "self.__bar", the Python interpreter sees the leading "__" and mangles it. It's the lightweight equivalent of a private attribute in other languages, with the difference that Python will let you attempt to access it anyway. But if you do, and it makes your code utterly brittle and prone to explosion, no one will give you sympathy or help you fix it. They're much more likely to tell you not to do that.


It's as close as they'll get to private methods while still having the "we're all consenting adults" philosophy that doesn't prevent you doing something dumb. Or if you use this and it breaks, you can't say you weren't warned.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: