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

preview_player
Показать описание

Leading underscores in Python variable names (for example _foo and __foo) protect developers from naming conflicts. In this video you'll learn how to work with these Pythonic coding conventions and why they exist.

A single underscore in front of a variable name (prefix) is a hint that a variable is meant for internal use only.

A double underscore prefix causes the Python interpreter to rewrite the variable name in order to avoid naming conflicts in subclasses. Double underscores are also called "dunders" in Python.

Watch the video tutorial to see the details of how double underscore name mangling works and how it affects your own Python classes.

* * *

FREE Python Tutorials & News:
Рекомендации по теме
Комментарии
Автор

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

LucasHartmann
Автор

... 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 x=1_2 gives x the value of 12. x=1, 000, 000 creates tuple (1, 0, 0), btw.

Chantillian
Автор

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

jamiemarshall
Автор

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

kenchen
Автор

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

sepehr
Автор

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

victorystocktv
Автор

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!

asands
Автор

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.

xaknitram
Автор

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

itzyourbwoytchybooxuur
Автор

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

andyanderson
Автор

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

KusogeMan
Автор

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

marunjimarunji
Автор

No real access restrictions. Geat language!

alexxx
Автор

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

theultimatereductionist
Автор

Ok, but what about the double underscore before and after a name __foo__ such as __init__? can u please explain it too.

barax
Автор

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.

easygerman
Автор

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

jeezboi
Автор

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

olexandrklymenko
Автор

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.

MidnightSt
Автор

Which editor are you using in this tutorial?

kanony