RUVIDEO
Поделитесь видео 🙏

How To: Name Mangling In Python (2 Min)

📁 Обучение 👁️ 18 📅 02.12.2023

In this tutorial, you'll learn how name mangling works in Python.


Facebook: https://www.facebook.com/GokceDBsql

Video Transcript:
_
Hi guys, this is Abhi from Gokcedb. In this video, you're going to learn how to name mangling works in Python. Let's start by looking at the authentication class. On line 2 I s special special, underscore underscore init, underscore underscore method to initialize two instance variables password and pass underscore phrase.

On line six, I have the decrypt method which returns the password if a correct pass underscore phrase is supplied. On line 12, I'm creating a new instance of the class authentication called off. On line 14, I'm calling the decrypt method passing the passphrase, and printing the return password.

If I executed this program, you'll see the password on the console. However, at the moment nothing is preventing me from accessing the password variable directly. So if I write, print auth dot password I should get the same result.

We could try prefixing the internal variables with an underscore but even then you can access the password by printing auth dot underscore password. However, if we prefix the internal variables with two underscores then python will perform name mangling. Le's see it in action.

Watch what happens when I try to print auth dot underscore underscore password I got an attribute error authentication object has no attribute underscore underscore password. When we use double underscores, the attribute gets prefixed by the underscore class name. So now, if I have to access the underscore underscore variable, I have to print auth dot underscore authentication underscore underscore password.

Even though name mangling doesn't guarantee privacy, it does send a strong message to other programmers to not touch the internal underscore underscore variables. There you have it. Make sure you like, subscribe, and turn on the notification bell until next time.

class Authentication:
def __init__(self, password, pass_phrase):
self.__password = password
self.__pass_phrase = pass_phrase

def decrypt(self, pass_phrase):
if pass_phrase == self.__pass_phrase:
return self.__password
else:
return ""


auth = Authentication("pa55w02d", "my new password")
print(auth.decrypt("my new password"))

print(auth._Authentication__password)

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How To: Name Mangling In Python (2 Min)», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.