Тёмный
No video :(

What's the meaning of underscores (_ & __) in Python variable names? 

Real Python
Подписаться 192 тыс.
Просмотров 424 тыс.
50% 1

Опубликовано:

 

20 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 279   
@LucasHartmann
@LucasHartmann 6 лет назад
For C++ people, foo is public, _bar is protected, and __baz is private.
@theonewhohonks9675
@theonewhohonks9675 6 лет назад
Finally it makes sense.
@karunesh26march
@karunesh26march 6 лет назад
no no Foo is public _bar is private and __baz is protected as user wants to use __baz in derived class
@LucasHartmann
@LucasHartmann 6 лет назад
@@karunesh26march __baz is name mangled, so it can only be used inside the class that defined it, not its derivatives. This is what private means in C++. _bar is not mangled, so it may be used elsewhere.
@barewr828
@barewr828 5 лет назад
oh thanks really much it really helped!
@spyrex3988
@spyrex3988 4 года назад
Thanks man
@rezaameli472
@rezaameli472 3 года назад
Python people decided to "simplify" things by not having private class members. Nicely done...
@maswinkels
@maswinkels 3 года назад
Yes. Terrible decision. I really love Python, but it has some ugly flaws.
@jamiemarshall8284
@jamiemarshall8284 6 лет назад
Thanks for this, its hard to find python explanations for devs that actually tell us whats under the hood. Much appreciated.
@realpython
@realpython 6 лет назад
You're welcome! I'm glad you found the explanation helpful.
@kenchen738
@kenchen738 6 лет назад
You just made me realize Dunder Mifflin is just a python variable name __Mifflin.
@realpython
@realpython 6 лет назад
Haha, that's great!
@jeremyheminger6882
@jeremyheminger6882 6 лет назад
I want to put that on a t-shirt!
@milanbhardwaj2917
@milanbhardwaj2917 3 года назад
That's what she said
@donaldli4755
@donaldli4755 3 года назад
I got here after a Dunder Mifflin run. Great Scott.
@MrClaudiodonate
@MrClaudiodonate 3 года назад
@@jeremyheminger6882 And if someone gets the t-shirt, INSTANT BONUS FRIEND!
@Chantillian
@Chantillian 4 года назад
... and if you want to impress your friends, there are also underscores in int values which arguably improve readability, but are ignored by Python. Eg: x = 1_000_000 gives us the integer-type variable x and its value 1000000. x=1_2 gives x the value of 12. x=1,000,000 creates tuple (1,0,0), btw.
@quads4407
@quads4407 3 года назад
Yes, thank you for reminding me that
@JorgetePanete
@JorgetePanete 3 года назад
same in java
@jcf20010
@jcf20010 3 года назад
Another item to add to the "Why I Don't Like Python List".
@sv8211
@sv8211 2 года назад
Tried it. My friend is unimpressed. 😞
@Chantillian
@Chantillian 2 года назад
@@sv8211 Not much of a friend, then. ;)
@asands123
@asands123 5 лет назад
At first I was like "This example is exactly like the one I just read in Python Tricks" before reading who published this video haha Subscribed!
@your-Space
@your-Space 4 года назад
Hi you are very intelligent 😉.
@rishabhrawat7856
@rishabhrawat7856 3 года назад
Your youtube account is younger than my brother...
@SOMEONE-eq5bu
@SOMEONE-eq5bu 3 года назад
Your acc is the oldest acc i have seen in youtube
@xaknitram
@xaknitram 6 лет назад
To elaborate on this explanation, avoiding name conflicts is the most important and missable use of the double underscore variable and function names. When a class is inherited from, any methods that the base class uses in its methods are searched for in the current scope (the new class). Therefore, if a method from the base class has been overwritten, the methods that call that method will call the new method instead of the old one, breaking the class. The double underscore system was implemented to fix this. For a crude example in python 3.6: class Temp: def get_temp() return "274 Kelvin" __get_temp = get_temp def display_temp(self): print(self.get_temp()) def display_temp2(self): print(self.__get_temp()) class Fahrenheit(Temp): def __init__(self): self.display_temp() # will display the current temperature in Fahrenheit now self.display_temp2() # will display the current temperature in Kelvin def get_temp(self): return "33.5 degrees Fahrenheit" As for making variables private, python tries to push user away from doing this. As Dan states, the underscores are mainly hints to other programmers. The @property decorator was implemented to this end.
@realpython
@realpython 6 лет назад
Thanks for sharing this!
@victorystocktv
@victorystocktv 4 года назад
00:21 here is the constructor of the class (생성자) 00:46 _ : underscore (single underscore) is to be treated as private by the programmer (private variable, so careful about changing), 파이썬은 public과 private 차이가 크지 않다. java에 비해 __ : dunder (double underscore) 4:13 t.Test__baz Thank you
@robinpage2730
@robinpage2730 2 года назад
Hey, you're getting a rendering bug with the characters in your comment, I saw a vid on that one, never thought I'd see it myself. The engine rendering RU-vid is reading the Unicode characters as utf-16, which are 16 bit characters. The bug comes from how the browser engine reads the endianness of utf-16: little-endian or big-endian. If it can't read the big-endian characters correctly it'll frame-shift and read the chars in the wrong bit order, as little-endian, rendering Chinese characters rather than English letters. Windows had a problem with this for a while
@andyanderson222
@andyanderson222 2 года назад
Good explanation, only suggestion is to use t.__dict__ instead of dir(t) since it won't return many builtin methods.
@theultimatereductionist7592
@theultimatereductionist7592 6 лет назад
THANK you for asking this question! I have NEVER used underscores in Python.
@realpython
@realpython 6 лет назад
You're welcome!
@MrRijoAlex
@MrRijoAlex 7 лет назад
Great explanation (Y). Thanks Dan.
@itzyourbwoytchybooxuur6475
@itzyourbwoytchybooxuur6475 5 лет назад
Thanks Dan. Simple and sweet as always. And I love your voice.
@realpython
@realpython 5 лет назад
Glad you enjoyed it!
@Hasan...
@Hasan... 3 года назад
That was Dunderful !
@alexxx4434
@alexxx4434 3 года назад
No real access restrictions. Geat language!
@KusogeMan
@KusogeMan 3 года назад
single underscore usually means private variable, double (dunder) means new classes will use the name mangling correctly with variables with same name dir() returns attributes
@avisinha6566
@avisinha6566 3 года назад
THANKS this help me understand.
@olexandrklymenko
@olexandrklymenko 6 лет назад
Hey Dan. Thanks for your great job. One minor comment: technically __init__ method is not a constructor. It rather 'initilizer'
@realpython
@realpython 6 лет назад
Thanks for pointing that out! Glad you enjoyed the video.
@sanjeevkumar-ty8dx
@sanjeevkumar-ty8dx 5 лет назад
Which py editor u r using???
@Cracks094
@Cracks094 3 года назад
why am i watching this at 2am i don't know the first thing about programming
@marunjimarunji8733
@marunjimarunji8733 10 месяцев назад
Thank you, the video covered everything I needed in a very convenient amount of time
@MidnightSt
@MidnightSt 3 года назад
I have seen stringly typing, we all have, php and js used to use it, but this is probably the first time I've ever seen stringly scoping.
@easygerman3402
@easygerman3402 2 года назад
Hi,Sir Dan.JV here again.Your video is really nice and I could understand everything,sir.I have view this video,like this video and subscribed the channel,sir.
@logannasty3240
@logannasty3240 3 года назад
I wish I was this clear when explaining concepts
@barax9462
@barax9462 4 года назад
Ok, but what about the double underscore before and after a name __foo__ such as __init__? can u please explain it too.
@mymoomin0952
@mymoomin0952 3 года назад
__thing__ is used for special built-in python functions, like init
@deViant14
@deViant14 3 года назад
it's a way for built-ins to get out of the way of you, the programmer, and out of your namespace
@rg.reboot.jam.edupro
@rg.reboot.jam.edupro 4 года назад
The explaination of dunder __baz doesnt make sense to me as a new developer ; for the same reason it could mangle the other 2 instance variables too (_bar or foo). Just the reason could be because the __ dunder has special meaning in python as its used for constructors & builtin language methods by convention it avoids the user defined names by name mangling
@mystery45454
@mystery45454 2 года назад
Thanks for making this useful video
@jeezboi5079
@jeezboi5079 3 года назад
This is such a nice video...clear concept, beautiful
@climbit9555
@climbit9555 3 года назад
I work a lot with dunder methods. But I need to call them in this weird way in my unittests
@kirasmith1147
@kirasmith1147 2 года назад
Possibly you can just unit test the "public/protected" methods, because the inner workings of your class will be revealed to be faulty if the outer facing thing that calls them fails
@Jason-uv5tm
@Jason-uv5tm 3 года назад
What does __baz__ mean
@lost-one
@lost-one 4 года назад
"Really the only reasonable way to get that done is to access them from the class itself". What about properties?
@joeking5211
@joeking5211 Год назад
Super informative, thks.
@bidochon2009
@bidochon2009 7 лет назад
nice video.... always been confused..not anymore !
@ManafKAMIL
@ManafKAMIL 3 года назад
It a nice explanation... but it raises another question now: what happens when inheriting from the class and defining new variables foo and _bar? wouldn't that causes naming conflicts and confusions too?
@KumarAbhinav2812
@KumarAbhinav2812 3 года назад
Yes, and that's the intent. You want foo to be publicly accessible, _bar be used in derived classes, and __baz to be available exclusively to one class.
@tomdorr9487
@tomdorr9487 4 года назад
I found this very insightful!
@MCChubbyUnicorn
@MCChubbyUnicorn 3 года назад
Nice. Basically how I treat my variables in other languages
@ImranHossain-fu4hj
@ImranHossain-fu4hj 3 года назад
Fabulous explanation as always. Thanks a lot
@FredoCorleone
@FredoCorleone 6 лет назад
There's only one _ worth mentioning: const _ = require('underscore')
@GodBurstPk
@GodBurstPk 3 года назад
Thanks for this, had a dual initiation bug where my configuration class was loaded twice when only calling the class once. seems this was a name mangeling issue.
@8koi245
@8koi245 3 года назад
I don't get it, gonna come back in a few weeks!
@EmileAI
@EmileAI 3 года назад
Come back
@eeriemyxi
@eeriemyxi 3 года назад
alright, 3 weeks when u coming back
@EmileAI
@EmileAI 3 года назад
@@eeriemyxi yeah, he/she needs to come back right fucking now!
@eeriemyxi
@eeriemyxi 3 года назад
@@EmileAI yep!
@dabananasauce7610
@dabananasauce7610 3 года назад
it has been 1 month, i require thy assistance
@javlontursunov6527
@javlontursunov6527 2 года назад
Hey bro please explain how to write double merged underscores
@gujjardachhora9862
@gujjardachhora9862 6 лет назад
Amazing explanation, cleared all my doubts
@realpython
@realpython 6 лет назад
I'm glad it was helpful!
@kunalsoni7681
@kunalsoni7681 3 года назад
wow new concept you explaining 😍
@cmac37420
@cmac37420 3 года назад
I would've loved to see what happens when you extend your Test class. Like would there be _Test__baz AND _extendedTest__baz or just the latter? I guess I'll have to go do it myself...
@vaiterius
@vaiterius 3 года назад
Thank you sir!
@AndrewErwin73
@AndrewErwin73 6 лет назад
Clear explanation of how Python is not object oriented. Does this still apply in Python 3.6? I know a lot of things changed. Wondering if this is one of them.
@malding1
@malding1 3 года назад
It could be though
@dreamscape1011
@dreamscape1011 4 года назад
Thank you sir, nice and clear!! :-)
@kanony5188
@kanony5188 3 года назад
Which editor are you using in this tutorial?
@jeancarlosadrianza876
@jeancarlosadrianza876 6 лет назад
Hi, Dan...Congratulations for your great job... Would you like to tell us what is your opinion about the few protection of the attributes (in objects) in python in comparation with Java? Do you think that this characteristic can be considered a defect of python?
@brpawankumariyengar4227
@brpawankumariyengar4227 6 лет назад
Excellent explanation ....Thank you very much Dan
@realpython
@realpython 6 лет назад
You're welcome!
@htgg9006
@htgg9006 Год назад
self.__mifflin='paper company'
@abir95571
@abir95571 3 года назад
_bar wont allow import * to itself ... not sure if it should be called protected . Even that can be bypassed by putting __all__=['_bar'] in the above code
@inteligenciaartificiuau
@inteligenciaartificiuau 6 месяцев назад
Amazing!
@thePronto
@thePronto 3 года назад
Yay! Subbed.
@leeritenour
@leeritenour 6 лет назад
Hi, How do you write multiple lines in python shell? How do you get auto-completion in python shell? Thanks.
@paschikshehu7988
@paschikshehu7988 6 лет назад
Yi-hsiu Lee Must be an IDE or text editor; python shell doesn't have text highlighting iirc
@oida10000
@oida10000 3 года назад
Now I understand why the magic functions do have this form. Do the ddash at end do something or is this just convention?
@sylvernale
@sylvernale 2 года назад
How do you get those sweet suggestions in your shell's python interpreter?
@dmm10000
@dmm10000 6 лет назад
vague - please expand on the suggestion that collisions could occur - how ?
@telegraph5592
@telegraph5592 6 лет назад
Ya, missed that a bit too. But there are comments explaining it. For example you may have a new class enhiring from the original one and defining a method which has a name already defined in the original class. In this case the new defined method will overwrite the one with same name from the original class. This may break the functionality of the original class enhireted unintentionally. To prevent that __ results in name mangeling preventing this Inbus.
@jamcdonald120
@jamcdonald120 3 года назад
but what if I want a variable named _Test__baz?
@saunakpandya7657
@saunakpandya7657 7 лет назад
Good explaining.👍
@DmitriiPetriev
@DmitriiPetriev 3 года назад
What interpreter you use? It’s give some tips when you type function. I have never seen that before.
@kumarvishalben
@kumarvishalben 3 года назад
Thanks
@Chatterphone
@Chatterphone 6 лет назад
Wonderful explanation, thank you!
@realpython
@realpython 6 лет назад
You're welcome!
@gulshankumar17
@gulshankumar17 3 года назад
thanks for the tutorial.
@shuntiiops5523
@shuntiiops5523 3 года назад
I have a quick question. If the given variable is 'Total Sale' when transformed into an underscore writing should it be written like this 'Total_Sale' or 'total_sale' or even 'Total_sale'? Which one's correct?
@noel.friedrich
@noel.friedrich 3 года назад
Generally you should not capitalise normal variables, so total_sale is the most agreed on
@luism55
@luism55 2 года назад
Someone tells me how to type this long underscore
@tarungarg2695
@tarungarg2695 5 лет назад
Nice video !! one doubt I have.. I heard in the video you said the one with a single underscore is private variable ? is that true? I believe the one with a single underscore is protected variable and the one with the double underscore is private.. please correct me if I am wrong.
@tesohh
@tesohh 3 года назад
How do you have syntax highlighting and suggestions?
@rangabharath4253
@rangabharath4253 6 лет назад
Hi Dan , Can u please make a video on how to extract a redirected url from a website using python other than beautiful soup☺👍
@TinkatheRainbowFox
@TinkatheRainbowFox 3 года назад
So tell us when do you use these and when you don't? What's the Best Practice or common conventions and the reasoning behind them?
@highxbye
@highxbye 3 года назад
I've found they are best used with the @property decorator, to prevent people from setting the variable when I only want to allow getting. class T(): def __init__(self): self._foo = 0 @property def foo(self): return self._foo t = T() t.foo -> 0 t.foo = 1 -> AttributeError: can't set attribute @property decorators can be used to do a lot more stuff but this was the basic explanation that opened the doors for me initially.
@letSimoo
@letSimoo 6 лет назад
wonderful explanation bro . . .Thx a lot
@realpython
@realpython 6 лет назад
You're welcome!
@UsmanGhani-wk6hq
@UsmanGhani-wk6hq Год назад
So for the encapsulation, should we use single underscore or double? Thanks.
@Schlumpfpirat
@Schlumpfpirat 5 лет назад
And everybody just wants to know which Sublime package you're using to show those information.
@ajitnayak9t99
@ajitnayak9t99 4 года назад
Bpython repl (alternative python interpreter)
@vpylr2806
@vpylr2806 4 года назад
Good explanation!!
@fc6827
@fc6827 3 года назад
I wonder if python devs are better at recognizing dunders compared to other devs
@divusiulius7539
@divusiulius7539 7 лет назад
is there a way to make the dunderscore(d) __names Immutable as in Scala val? val x: Int = 0 or val x: String = "Immutable_String"
@harmitalestari5592
@harmitalestari5592 3 года назад
Hi, sir.. How to remove these underscore?
@gavinpereira6588
@gavinpereira6588 3 года назад
Anybody know what console / editor this is. It looks pretty cool
@firewaterrise9412
@firewaterrise9412 6 лет назад
Informative... thanks, Man.
@realpython
@realpython 6 лет назад
You're welcome!
@Westkane11
@Westkane11 3 года назад
Thanks great video. Honestly python is a language with some really bad designs. The using _ instead of declaring the scope just leads to more difficult code to read and i really don't understand, why they thougt it was a good idea to use white space for scoping the code.
@pranavnyavanandi9710
@pranavnyavanandi9710 2 года назад
How are we able to access magic methods normally then? Are they not name mangled? That is, "Hello".__len__() "Hello"._str__len__() The first one works fine despite being a private method. The second I never tried.
@jonron3805
@jonron3805 3 года назад
Cant we use super to access the __baz?
@Alexxx160994
@Alexxx160994 7 лет назад
Great voice and great microphone. Which one are you using?
@Alexxx160994
@Alexxx160994 7 лет назад
You're right :)
@realpython
@realpython 7 лет назад
Thanks! I used the ATR 2100 USB for this video: dbader.org/resources/#screencasting
@famouscloud1292
@famouscloud1292 7 лет назад
what mic are u using ? sounds great
@ndukwejoe123
@ndukwejoe123 6 лет назад
thanks for the explaination
@realpython
@realpython 6 лет назад
You're welcome! :-)
@JonDisnard
@JonDisnard 2 года назад
Please correct me if wrong, but I was under the impression the __init__ is merely an initializer, where __new__ is the underlying constructor?
@pranavnyavanandi9710
@pranavnyavanandi9710 2 года назад
__init__ is the constructor. __new__ creates the instance. __init__ initializes it.
@finderlandrs7965
@finderlandrs7965 3 года назад
Does it change if underscore comes after variable name (i.e. bar_, foo_)?
@deimuader
@deimuader 3 года назад
no
@ngolian
@ngolian 3 года назад
Now I want to call all my variables __mifflin.
@DynoosHD
@DynoosHD 3 года назад
So how would be the correct way to access __baz ?
@michael_p
@michael_p 3 года назад
You should access __baz only inside its class. Use it for internal helping methods or attributes, that are not part of the public interface, and must not be altered/overridden through inheritance.
@aalapjethwa6452
@aalapjethwa6452 5 лет назад
Nice explanation
@realpython
@realpython 5 лет назад
Thanks!
@KrishnaManohar8021
@KrishnaManohar8021 4 года назад
Object vs instance???
@Mrstealurgrill
@Mrstealurgrill 3 года назад
You didn’t show how to access the __baz variable via class
@capsujit
@capsujit 6 лет назад
awesome explanation....
@realpython
@realpython 6 лет назад
Glad you liked it!
@thinhzawsze7519
@thinhzawsze7519 6 лет назад
Good explanation!! I wonder which IDE you are using....
@realpython
@realpython 6 лет назад
I use Sublime Text 3 :)
@RomanDryndik
@RomanDryndik 3 года назад
What shell do you use?
@michtesar
@michtesar 7 лет назад
Awesome. Which IDE you use for macOS? Thank you and have nice day.
@realpython
@realpython 7 лет назад
Hey Michael, I use Sublime Text with a bunch of plugins. This is my setup: SublimeTextPython.com
@dasgoll
@dasgoll 6 лет назад
Python Training by Dan Bader So you are using the console that comes with Sublime to execute those commands?
@meanmole3212
@meanmole3212 6 лет назад
Hmm, I used to think _ is protected and __ is private...
@cruepprich
@cruepprich 6 лет назад
Well done. Thx.
@realpython
@realpython 6 лет назад
You're welcome!
@richardhutchinson4663
@richardhutchinson4663 3 года назад
You did not show how to access the dunder bazz __baz within the class. Do you use the class name, then dot notation to get to __baz? Example: Test.__baz >>> 42 Is this how to get the 42?
@souvikghosh6966
@souvikghosh6966 3 года назад
t._Test__baz, where t=Test()
@richardhutchinson4663
@richardhutchinson4663 3 года назад
@@souvikghosh6966 Thanks.
@TheNorthRemember
@TheNorthRemember 3 года назад
i still dont get it
@3mariusss
@3mariusss 6 лет назад
can this be classed as polymorphism?
@ZacharySmith89
@ZacharySmith89 6 лет назад
For a longer explanation of the purpose of _ _: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-HTLu2DFOdTg.html (starting around 35:00)
@lilacdoe7945
@lilacdoe7945 3 года назад
What IDE is this?
Далее
Every Python dev falls for this (name mangling)
14:11
Просмотров 138 тыс.
Vladimir Putinin Bakıda rəsmi qarşılanma mərasimi
13:06
What are various underscores used in python​?
21:26
Python Decorators in 15 Minutes
15:14
Просмотров 437 тыс.
__new__ vs __init__ in Python
10:50
Просмотров 207 тыс.
Functions vs Classes: When to Use Which and Why?
10:49
Просмотров 152 тыс.
Top 18 Most Useful Python Modules
10:50
Просмотров 928 тыс.
25 nooby Python habits you need to ditch
9:12
Просмотров 1,7 млн
Optional Arguments in Python With *args and **kwargs
10:44
super/MRO, Python's most misunderstood feature.
21:07
Просмотров 216 тыс.
Vladimir Putinin Bakıda rəsmi qarşılanma mərasimi
13:06