@@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.
... 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.
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.
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
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
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
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
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.
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?
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.
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.
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?
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?
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.
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
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...
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.
_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
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.
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.
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.
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.
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?
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 ?
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.
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
For C++ people, foo is public, _bar is protected, and __baz is private.
Finally it makes sense.
no no Foo is public _bar is private and __baz is protected as user wants to use __baz in derived class
@@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.
oh thanks really much it really helped!
Thanks man
Thanks for this, its hard to find python explanations for devs that actually tell us whats under the hood. Much appreciated.
You're welcome! I'm glad you found the explanation helpful.
Python people decided to "simplify" things by not having private class members. Nicely done...
Yes. Terrible decision. I really love Python, but it has some ugly flaws.
... 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.
Yes, thank you for reminding me that
same in java
Another item to add to the "Why I Don't Like Python List".
Tried it. My friend is unimpressed. 😞
@@sv8211 Not much of a friend, then. ;)
You just made me realize Dunder Mifflin is just a python variable name __Mifflin.
Haha, that's great!
I want to put that on a t-shirt!
That's what she said
I got here after a Dunder Mifflin run. Great Scott.
@@jeremyheminger6882 And if someone gets the t-shirt, INSTANT BONUS FRIEND!
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!
Hi you are very intelligent 😉.
Your youtube account is younger than my brother...
Your acc is the oldest acc i have seen in youtube
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.
Thanks for sharing this!
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
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
Good explanation, only suggestion is to use t.__dict__ instead of dir(t) since it won't return many builtin methods.
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
THANKS this help me understand.
Thank you, the video covered everything I needed in a very convenient amount of time
THANK you for asking this question! I have NEVER used underscores in Python.
You're welcome!
Thanks Dan. Simple and sweet as always. And I love your voice.
Glad you enjoyed it!
That was Dunderful !
No real access restrictions. Geat language!
Great explanation (Y). Thanks Dan.
Hey Dan. Thanks for your great job. One minor comment: technically __init__ method is not a constructor. It rather 'initilizer'
Thanks for pointing that out! Glad you enjoyed the video.
Which py editor u r using???
Ok, but what about the double underscore before and after a name __foo__ such as __init__? can u please explain it too.
__thing__ is used for special built-in python functions, like init
it's a way for built-ins to get out of the way of you, the programmer, and out of your namespace
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
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.
Thanks for making this useful video
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?
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.
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.
Which editor are you using in this tutorial?
What interpreter you use? It’s give some tips when you type function. I have never seen that before.
Super informative, thks.
This is such a nice video...clear concept, beautiful
Hi,
How do you write multiple lines in python shell?
How do you get auto-completion in python shell?
Thanks.
Yi-hsiu Lee Must be an IDE or text editor; python shell doesn't have text highlighting iirc
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.
It could be though
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?
Generally you should not capitalise normal variables, so total_sale is the most agreed on
So for the encapsulation, should we use single underscore or double? Thanks.
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?
"Really the only reasonable way to get that done is to access them from the class itself". What about properties?
Hey bro please explain how to write double merged underscores
How do you get those sweet suggestions in your shell's python interpreter?
There's only one _ worth mentioning: const _ = require('underscore')
Fabulous explanation as always. Thanks a lot
Please correct me if wrong, but I was under the impression the __init__ is merely an initializer, where __new__ is the underlying constructor?
__init__ is the constructor. __new__ creates the instance. __init__ initializes it.
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.
I work a lot with dunder methods. But I need to call them in this weird way in my unittests
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
what mic are u using ? sounds great
How do you have syntax highlighting and suggestions?
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...
Thank you sir!
why am i watching this at 2am i don't know the first thing about programming
Now I understand why the magic functions do have this form. Do the ddash at end do something or is this just convention?
I found this very insightful!
Does it change if underscore comes after variable name (i.e. bar_, foo_)?
no
wow new concept you explaining 😍
Are you using an IDE such as PyCharm or are you doing this from the command prompt?
I use Sublime Text as my main IDE.
What does __baz__ mean
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.
Excellent explanation ....Thank you very much Dan
You're welcome!
Amazing explanation, cleared all my doubts
I'm glad it was helpful!
_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
Amazing!
Hi, sir.. How to remove these underscore?
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"
nice video.... always been confused..not anymore !
I don't get it, gonna come back in a few weeks!
Come back
alright, 3 weeks
when u coming back
@@eeriemyxi yeah, he/she needs to come back right fucking now!
@@EmileAI yep!
it has been 1 month, i require thy assistance
but what if I want a variable named _Test__baz?
Anybody know what console / editor this is. It looks pretty cool
Awesome. Which IDE you use for macOS? Thank you and have nice day.
Hey Michael, I use Sublime Text with a bunch of plugins. This is my setup: SublimeTextPython.com
Python Training by Dan Bader So you are using the console that comes with Sublime to execute those commands?
Thanks
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.
vague - please expand on the suggestion that collisions could occur - how ?
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.
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.
Great voice and great microphone. Which one are you using?
You're right :)
Thanks! I used the ATR 2100 USB for this video: dbader.org/resources/#screencasting
Nice. Basically how I treat my variables in other languages
Wonderful explanation, thank you!
You're welcome!
Thank you sir, nice and clear!! :-)
What shell do you use?
Good explanation!! I wonder which IDE you are using....
I use Sublime Text 3 :)
And everybody just wants to know which Sublime package you're using to show those information.
Bpython repl (alternative python interpreter)
wonderful explanation bro . . .Thx a lot
You're welcome!
Good explanation!!
So how would be the correct way to access __baz ?
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.
thanks for the tutorial.
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?
t._Test__baz, where t=Test()
@@souvikghosh6966 Thanks.
Cant we use super to access the __baz?
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 ?
No, it isn't
Good explaining.👍
I wish I was this clear when explaining concepts
Nice explanation
Thanks!
Informative... thanks, Man.
You're welcome!
Hi Dan , Can u please make a video on how to extract a redirected url from a website using python other than beautiful soup☺👍
What kind of programs or software are made with python ????
There are quite a few made with Python, I recommend giving this a read: realpython.com/world-class-companies-using-python/
Which extensions do you have in sublime text 3 for python?
awesome explanation....
Glad you liked it!
Hi Dan
Can you please tell me if I can use IntelliJ for learning python instead of sublime editor?
Hey, yes you can use IntelliJ! Whatever works best for you is the right choice. :)
can this be classed as polymorphism?
what is the screen casting software you used? Cheers
Here is a list of screen-casting software I use: dbader.org/resources/#screencasting
thanks for the explaination
You're welcome! :-)
I wonder if python devs are better at recognizing dunders compared to other devs
You didn’t show how to access the __baz variable via class
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?
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.
self.__mifflin='paper company'
Hmm, I used to think _ is protected and __ is private...
Excellent explanation as always, Dan. Do you have any examples of when you’ve used dunder in production?
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
Well done. Thx.
You're welcome!