Python actually DOES have private attributes (sort of)

preview_player
Показать описание
This definitely has to be one of the weirder parts of Python.

0:00 - Intro
0:50 - What are these "private attributes" (and methods)?
4:02 - Throw people off a little more by overloading __dir__
6:10 - Are they statically type-safe?
6:38 - Preventing name collisions
8:19 - How you *should* define "private" attributes
8:30 - Using properties as getters and setters
9:49 - Outro



If you enjoy my content, consider supporting me on Patreon or becoming a member!

If you need help with anything, feel free to join the Discord server:

I get a lot of people asking, so here's my Visual Studio Code setup!



If you have any questions, don't hesitate to ask in the comments! I'll try and answer as soon as I can, providing someone else hasn't already done so.

#python #coding #howto
Рекомендации по теме
Комментарии
Автор

It's useful in the scenario where you may have multiple inheritance or diamond inheritance. There's no guarantee that some other class in the class hierarchy won't also want to store a instance variable with the same name, so double-underscore is syntactic sugar/a shorthand way of giving each class a semi-private namespace to store instance variables.

I think of single underscore as protected, and double underscore as private, both are only weak guarantees (as you demonstrate in this video) as nothing stops external code from accessing them if it's being persistent. This is true also for bypassing the __dir__ override, because the instance variable can be found via __dict__.

nurmr
Автор

I encountered this a while ago after I first heard about private in languages like Java. There is a temptation to hide as much as possible from the outside, but ultimately, you shouldn't have to protect your code from being used in an unintended way. I like the pattern of using a single underscore to mark an internal attribute as it quite clearly delineates what is normal use and unintended use. This also allows you to easily modify the internals of a library if you know what you are doing without having to hack around name mangling or other measures.

aurorusidk
Автор

1:53 If it wasn't for code completion in PyCharm, I would probably never type this right.

Indently
Автор

Don't call name mangling private ever again you're disrespectful to python.

yorailevi
welcome to shbcf.ru