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

Поделиться
HTML-код
  • Опубликовано: 8 ноя 2024

Комментарии • 277

  • @LucasHartmann
    @LucasHartmann 6 лет назад +926

    For C++ people, foo is public, _bar is protected, and __baz is private.

    • @theonewhohonks9675
      @theonewhohonks9675 6 лет назад +80

      Finally it makes sense.

    • @karunesh26march
      @karunesh26march 6 лет назад +26

      no no Foo is public _bar is private and __baz is protected as user wants to use __baz in derived class

    • @LucasHartmann
      @LucasHartmann 6 лет назад +63

      @@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 года назад +2

      Thanks man

  • @jamiemarshall8284
    @jamiemarshall8284 6 лет назад +100

    Thanks for this, its hard to find python explanations for devs that actually tell us whats under the hood. Much appreciated.

    • @realpython
      @realpython  6 лет назад +11

      You're welcome! I'm glad you found the explanation helpful.

  • @sepehr11235
    @sepehr11235 3 года назад +175

    Python people decided to "simplify" things by not having private class members. Nicely done...

    • @maswinkels
      @maswinkels 3 года назад +10

      Yes. Terrible decision. I really love Python, but it has some ugly flaws.

  • @Chantillian
    @Chantillian 4 года назад +50

    ... 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 года назад +4

      Yes, thank you for reminding me that

    • @JorgetePanete
      @JorgetePanete 3 года назад +1

      same in java

    • @jcf20010
      @jcf20010 3 года назад +4

      Another item to add to the "Why I Don't Like Python List".

    • @sv8211
      @sv8211 3 года назад

      Tried it. My friend is unimpressed. 😞

    • @Chantillian
      @Chantillian 3 года назад

      @@sv8211 Not much of a friend, then. ;)

  • @kenchen738
    @kenchen738 6 лет назад +736

    You just made me realize Dunder Mifflin is just a python variable name __Mifflin.

    • @realpython
      @realpython  6 лет назад +62

      Haha, that's great!

    • @jeremyheminger6882
      @jeremyheminger6882 6 лет назад +20

      I want to put that on a t-shirt!

    • @milanbhardwaj2917
      @milanbhardwaj2917 4 года назад +12

      That's what she said

    • @donaldli4755
      @donaldli4755 3 года назад +2

      I got here after a Dunder Mifflin run. Great Scott.

    • @MrClaudiodonate
      @MrClaudiodonate 3 года назад +1

      @@jeremyheminger6882 And if someone gets the t-shirt, INSTANT BONUS FRIEND!

  • @asands123
    @asands123 5 лет назад +72

    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!

    • @Fahadkhan_313
      @Fahadkhan_313 4 года назад +1

      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 лет назад +14

    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 лет назад +2

      Thanks for sharing this!

  • @victorystocktv
    @victorystocktv 4 года назад +12

    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 года назад +1

      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 RUclips 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 3 года назад +4

    Good explanation, only suggestion is to use t.__dict__ instead of dir(t) since it won't return many builtin methods.

  • @KusogeMan
    @KusogeMan 3 года назад +1

    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 года назад +1

      THANKS this help me understand.

  • @marunjimarunji8733
    @marunjimarunji8733 Год назад

    Thank you, the video covered everything I needed in a very convenient amount of time

  • @theultimatereductionist7592
    @theultimatereductionist7592 6 лет назад +9

    THANK you for asking this question! I have NEVER used underscores in Python.

  • @itzyourbwoytchybooxuur6475
    @itzyourbwoytchybooxuur6475 5 лет назад +5

    Thanks Dan. Simple and sweet as always. And I love your voice.

  • @Hasan...
    @Hasan... 3 года назад +18

    That was Dunderful !

  • @alexxx4434
    @alexxx4434 3 года назад

    No real access restrictions. Geat language!

  • @MrRijoAlex
    @MrRijoAlex 7 лет назад +30

    Great explanation (Y). Thanks Dan.

  • @olexandrklymenko
    @olexandrklymenko 6 лет назад +16

    Hey Dan. Thanks for your great job. One minor comment: technically __init__ method is not a constructor. It rather 'initilizer'

    • @realpython
      @realpython  6 лет назад +6

      Thanks for pointing that out! Glad you enjoyed the video.

    • @sanjeevkumar-ty8dx
      @sanjeevkumar-ty8dx 6 лет назад

      Which py editor u r using???

  • @barax9462
    @barax9462 4 года назад +14

    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 года назад +6

      __thing__ is used for special built-in python functions, like init

    • @deViant14
      @deViant14 3 года назад +9

      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 года назад +2

    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

  • @easygerman3402
    @easygerman3402 3 года назад

    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.

  • @mystery45454
    @mystery45454 3 года назад

    Thanks for making this useful video

  • @ManafKAMIL
    @ManafKAMIL 3 года назад +2

    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 года назад +1

      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.

  • @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.

  • @kanony5188
    @kanony5188 3 года назад +3

    Which editor are you using in this tutorial?

  • @DmitriiPetriev
    @DmitriiPetriev 3 года назад

    What interpreter you use? It’s give some tips when you type function. I have never seen that before.

  • @joeking5211
    @joeking5211 Год назад

    Super informative, thks.

  • @jeezboi5079
    @jeezboi5079 3 года назад

    This is such a nice video...clear concept, beautiful

  • @leeritenour
    @leeritenour 6 лет назад +3

    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

  • @AndrewErwin73
    @AndrewErwin73 6 лет назад +1

    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

  • @shuntiiops5523
    @shuntiiops5523 4 года назад +1

    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 года назад +2

      Generally you should not capitalise normal variables, so total_sale is the most agreed on

  • @UsmanGhani-wk6hq
    @UsmanGhani-wk6hq 2 года назад

    So for the encapsulation, should we use single underscore or double? Thanks.

  • @jeancarlosadrianza876
    @jeancarlosadrianza876 7 лет назад +2

    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?

  • @lost-one
    @lost-one 4 года назад +3

    "Really the only reasonable way to get that done is to access them from the class itself". What about properties?

  • @javlontursunov6527
    @javlontursunov6527 3 года назад

    Hey bro please explain how to write double merged underscores

  • @sylvernale
    @sylvernale 2 года назад

    How do you get those sweet suggestions in your shell's python interpreter?

  • @FredoCorleone
    @FredoCorleone 6 лет назад +1

    There's only one _ worth mentioning: const _ = require('underscore')

  • @ImranHossain-fu4hj
    @ImranHossain-fu4hj 3 года назад

    Fabulous explanation as always. Thanks a lot

  • @JonDisnard
    @JonDisnard 3 года назад

    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.

  • @tarungarg2695
    @tarungarg2695 5 лет назад +3

    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.

  • @climbit9555
    @climbit9555 3 года назад +7

    I work a lot with dunder methods. But I need to call them in this weird way in my unittests

    • @kirasmith1147
      @kirasmith1147 3 года назад

      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

  • @famouscloud1292
    @famouscloud1292 7 лет назад +1

    what mic are u using ? sounds great

  • @tesohh
    @tesohh 3 года назад

    How do you have syntax highlighting and suggestions?

  • @GrecianGoat
    @GrecianGoat 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!

  • @Cracks094
    @Cracks094 3 года назад +7

    why am i watching this at 2am i don't know the first thing about programming

  • @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?

  • @tomdorr9487
    @tomdorr9487 4 года назад +2

    I found this very insightful!

  • @finderlandrs7965
    @finderlandrs7965 3 года назад +1

    Does it change if underscore comes after variable name (i.e. bar_, foo_)?

  • @kunalsoni7681
    @kunalsoni7681 3 года назад

    wow new concept you explaining 😍

  • @BoxerDogs
    @BoxerDogs 6 лет назад +1

    Are you using an IDE such as PyCharm or are you doing this from the command prompt?

    • @realpython
      @realpython  6 лет назад +3

      I use Sublime Text as my main IDE.

  • @Jason-uv5tm
    @Jason-uv5tm 3 года назад +1

    What does __baz__ mean

  • @GodBurstPk
    @GodBurstPk 3 года назад +1

    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.

  • @brpawankumariyengar4227
    @brpawankumariyengar4227 6 лет назад

    Excellent explanation ....Thank you very much Dan

  • @gujjardachhora9862
    @gujjardachhora9862 6 лет назад +1

    Amazing explanation, cleared all my doubts

  • @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 9 месяцев назад

    Amazing!

  • @harmitalestari5592
    @harmitalestari5592 3 года назад

    Hi, sir.. How to remove these underscore?

  • @divusiulius7539
    @divusiulius7539 7 лет назад +1

    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"

  • @bidochon2009
    @bidochon2009 7 лет назад +4

    nice video.... always been confused..not anymore !

  • @8koi245
    @8koi245 3 года назад +7

    I don't get it, gonna come back in a few weeks!

    • @EmileAI
      @EmileAI 3 года назад

      Come back

    • @eeriemyxi
      @eeriemyxi 3 года назад +1

      alright, 3 weeks
      when u coming back

    • @EmileAI
      @EmileAI 3 года назад

      @@eeriemyxi yeah, he/she needs to come back right fucking now!

    • @eeriemyxi
      @eeriemyxi 3 года назад +1

      @@EmileAI yep!

    • @dabananasauce7610
      @dabananasauce7610 3 года назад +1

      it has been 1 month, i require thy assistance

  • @jamcdonald120
    @jamcdonald120 3 года назад

    but what if I want a variable named _Test__baz?

  • @gavinpereira6588
    @gavinpereira6588 3 года назад

    Anybody know what console / editor this is. It looks pretty cool

  • @michtesar
    @michtesar 7 лет назад +1

    Awesome. Which IDE you use for macOS? Thank you and have nice day.

    • @realpython
      @realpython  7 лет назад +2

      Hey Michael, I use Sublime Text with a bunch of plugins. This is my setup: SublimeTextPython.com

    • @dasgoll
      @dasgoll 6 лет назад +1

      Python Training by Dan Bader So you are using the console that comes with Sublime to execute those commands?

  • @kumarvishalben
    @kumarvishalben 3 года назад

    Thanks

  • @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.

  • @dmm10000
    @dmm10000 6 лет назад +2

    vague - please expand on the suggestion that collisions could occur - how ?

    • @telegraph5592
      @telegraph5592 6 лет назад +2

      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.

  • @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.

  • @Alexxx160994
    @Alexxx160994 7 лет назад +1

    Great voice and great microphone. Which one are you using?

    • @Alexxx160994
      @Alexxx160994 7 лет назад +1

      You're right :)

    • @realpython
      @realpython  7 лет назад +1

      Thanks! I used the ATR 2100 USB for this video: dbader.org/resources/#screencasting

  • @MCChubbyUnicorn
    @MCChubbyUnicorn 3 года назад +1

    Nice. Basically how I treat my variables in other languages

  • @Chatterphone
    @Chatterphone 6 лет назад

    Wonderful explanation, thank you!

  • @dreamscape1011
    @dreamscape1011 4 года назад +1

    Thank you sir, nice and clear!! :-)

  • @RomanDryndik
    @RomanDryndik 3 года назад

    What shell do you use?

  • @thinhzawsze7519
    @thinhzawsze7519 6 лет назад

    Good explanation!! I wonder which IDE you are using....

  • @Schlumpfpirat
    @Schlumpfpirat 5 лет назад +1

    And everybody just wants to know which Sublime package you're using to show those information.

    • @ajitnayak9t99
      @ajitnayak9t99 4 года назад

      Bpython repl (alternative python interpreter)

  • @letSimoo
    @letSimoo 6 лет назад

    wonderful explanation bro . . .Thx a lot

  • @vpylr2806
    @vpylr2806 4 года назад

    Good explanation!!

  • @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.

  • @gulshankumar17
    @gulshankumar17 3 года назад

    thanks for the tutorial.

  • @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?

  • @jonron3805
    @jonron3805 3 года назад

    Cant we use super to access the __baz?

  • @sarahbiebah
    @sarahbiebah 6 лет назад +1

    is the concept of "dunder" variables in Python similar to the concept of Polymorphism in C++ ? In other words, is it a technique to call a specific foo() function in one class if foo() exists with the same name in many other classes - therefore acting as a corresponding syntax to C++'s "virtual" keyword ?

    • @saulaxel
      @saulaxel 6 лет назад +1

      No, it isn't

  • @saunakpandya7657
    @saunakpandya7657 7 лет назад +1

    Good explaining.👍

  • @logannasty3240
    @logannasty3240 3 года назад

    I wish I was this clear when explaining concepts

  • @aalapjethwa6452
    @aalapjethwa6452 6 лет назад

    Nice explanation

  • @firewaterrise9412
    @firewaterrise9412 6 лет назад

    Informative... thanks, Man.

  • @rangabharath4253
    @rangabharath4253 7 лет назад +1

    Hi Dan , Can u please make a video on how to extract a redirected url from a website using python other than beautiful soup☺👍

  • @jackschlessinger3447
    @jackschlessinger3447 5 лет назад

    What kind of programs or software are made with python ????

    • @realpython
      @realpython  5 лет назад

      There are quite a few made with Python, I recommend giving this a read: realpython.com/world-class-companies-using-python/

  • @parthdodiya8448
    @parthdodiya8448 6 лет назад +2

    Which extensions do you have in sublime text 3 for python?

  • @capsujit
    @capsujit 6 лет назад

    awesome explanation....

  • @megoo401
    @megoo401 6 лет назад

    Hi Dan
    Can you please tell me if I can use IntelliJ for learning python instead of sublime editor?

    • @realpython
      @realpython  6 лет назад +1

      Hey, yes you can use IntelliJ! Whatever works best for you is the right choice. :)

  • @3mariusss
    @3mariusss 6 лет назад

    can this be classed as polymorphism?

  • @ChubbaStun
    @ChubbaStun 6 лет назад

    what is the screen casting software you used? Cheers

    • @realpython
      @realpython  6 лет назад

      Here is a list of screen-casting software I use: dbader.org/resources/#screencasting

  • @ndukwejoe123
    @ndukwejoe123 7 лет назад

    thanks for the explaination

  • @fc6827
    @fc6827 3 года назад

    I wonder if python devs are better at recognizing dunders compared to other devs

  • @Mrstealurgrill
    @Mrstealurgrill 3 года назад

    You didn’t show how to access the __baz variable via class

  • @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.

  • @htgg9006
    @htgg9006 2 года назад +1

    self.__mifflin='paper company'

  • @meanmole3212
    @meanmole3212 6 лет назад

    Hmm, I used to think _ is protected and __ is private...

  • @SHKEVE
    @SHKEVE 6 лет назад

    Excellent explanation as always, Dan. Do you have any examples of when you’ve used dunder in production?

    • @realpython
      @realpython  6 лет назад

      I do not currently have any posted, I appreciate the suggestion! In the mean time you may enjoy this write up on dunder as well: dbader.org/blog/python-dunder-methods

  • @cruepprich
    @cruepprich 6 лет назад

    Well done. Thx.