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
On this page of the site you can watch the video online DO YOU KNOW? What is Name-Mangling in Python! with a duration of hours minute second in good quality, which was uploaded by the user PyMastery Community 27 June 2023, share the link with friends and acquaintances, this video has already been watched 444 times on youtube and it was liked by 14 viewers. Enjoy your viewing!