DO YOU KNOW? What is Name-Mangling in Python!

Publicado el: 27 junio 2023
en el canal de: PyMastery Community
444
14

DO YOU KNOW? What is Name-Mangling in Python! #python #shorts #programming #coding

Hey there, Python enthusiasts! Are you curious about accessing private variables in Python? Let's dive in.

In this example, we have three classes: Male, Female, and SexDetermination. Each class has a private attribute representing the chromosome. But can we access these private variables directly? Let's find out!
If we try to access a private variable directly, like Male.__chromosome, we encounter an AttributeError. Python protects these variables to maintain encapsulation. But, Anyhow we want to access those?

By using name-mangling, we can access these private variables indirectly. Now, if we use the syntax 'ClassName._ClassName__variable', we can retrieve the values of private variables. Let's see it in action!

Voila! We can access the private variable '__chromosome' in the Male class using 'Male._Male__chromosome'. The same applies to the Female class. And same goes for SexDetermination.

When we inspect the class using 'dir(SexDetermination)', we can see the power and effect of name-mangling in action. It maintains encapsulation, prevents naming conflicts, and gives us better control over accessing private variables. Thats all in this video. Thanks for watching.



class Male:
__chromosome = 'XY'

class Female:
__chromosome = 'XX'

class SexDetermination(Male, Female):
__chromosome = 'XXY'

print(Male.__chromosome)

print(Male._Male__chromosome)
print(Female._Female__chromosome)

print(SexDetermination._Male__chromosome)
print(SexDetermination._Female__chromosome)
print(SexDetermination._SexDetermination__chromosome)
print(dir(SexDetermination))

name mangling, the purpose of name mangling is to avoid, name mangling in python, python name mangling, private variables in python, encapsulation, data hiding, python 3.11,
pymastery community, #pymasterycommunity, python3, python 3.11,
#python, #python3 , #programming , #coding , #pythonshorts , #shortsvideo , #short, #shorts, #shortsfeed , #youtubeshorts , print python, python print, print, question, #question


En esta página del sitio puede ver el video en línea DO YOU KNOW? What is Name-Mangling in Python! de Duración hora minuto segunda en buena calidad , que subió el usuario PyMastery Community 27 junio 2023, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 444 veces y le gustó 14 a los espectadores. Disfruta viendo!