• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Name Mangling in Python with Example

Aniruddha Chaudhari/13713/4
CodePython

Going through this complete tutorial, you will learn one of the very important concepts- Python Name Mangling.

It’s not so difficult as it seems to be if you follow this complete tutorial and executing the code I have shared in this tutorial.

Let’s begin.

Table of Contents

  • Purpose of Name Mangling in Python
  • What is Name Mangling in Python?
  • Simple Class Example
  • Python Name Mangling with Function Name
  • Use of Name Mangling in Function Overriding

Purpose of Name Mangling in Python

In Python programming, you can provide the access modifier (public/private) to the class members (variable or function).

Basically, an access modifier is used to define- whether the given to class members should be accessible to outside the class or not.

In most of the programming, if you mention access modifier as private for any class members, your program cannot access that class member outside of the class.

As Python doesn’t have an access modifier, you can not restrict the class members from getting access outside of the class.

To overcome this, Python has a concept Name Mangling.

Don’t bother. I will explain it in a very simple manner- step-by-step

What is Name Mangling in Python?

Let’s take a simple class example to define the name mangling.

class myClass:
  def __init__(self):
    self.x=10
    self.__y=20

obj=myClass()
print(obj.__y)

You will get an error as

Traceback (most recent call last):
File "/home/1af1225c50e8214f40613eda2aa27751.py", line 7, in <module>
print(obj.__y)
AttributeError: 'myClass' object has no attribute '__y'

Even though we have initialized __y variable inside the __init__(), you can not access it outside of the class using the object.

Adding __ as a prefix makes member private.

Why is there no attribute associated with the object obj?

Let’s see all the attributes associated with the object obj.

You can simply print all the attributes that correspond to the object using dir() method.

Here is a simple program.

class myClass:
  def __init__(self):
    self.x=10
    self.__y=20

obj=myClass()
print(dir(obj))

Output.

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_myClass__y', 'x']

If you look at the output list, there is no attribute __y.  Whereas, attribute x that we have initialized is present.

Interestingly, instead of __y, you can find the attribute _myClass__y.

While executing your program, the name of the attribute __y is renamed to _myClass__y.

Every attribute prefixed with __ (double underscores) will be changed to _<class_name><atribute_name>

This concept is called the name mangling in Python.

Simple Class Example

Here is your program. You can rewrite to access the name mangling attribute.

class myClass:
  def __init__(self):
    self.x=10
    self.__y=20

obj=myClass()
print(obj._myClass__y)

Output:

20

In the above example, I explained to you the name mangling for the variable attribute. This concept also holds true for the function name.

Python Name Mangling with Function Name

Python underscore prefix function.

Try this simple Python class function.

class myClass:
  def myFunc(self):
    print("Hello, World!")

obj=myClass()
obj.myFunc()

Output:

Hello, Wolrd!

Now rename function name from myFunc() to __myFunc() and run the program again.

class myClass:
  def __myFunc(self):
    print("Hello World!")

obj=myClass()
obj.__myFunc()

Output:

Traceback (most recent call last):
File "/home/22c0364aa126811fe5f362040f5a1c91.py", line 7, in <module>
obj.__myFunc()
AttributeError: 'myClass' object has no attribute __myFunc

As you have given __ before the function name, as per the name mangling concept in Python, this function name is renamed to _myClass__myFunc().

class myClass:
  def __myFunc(self):
    print("Hello, World!")

obj=myClass()
obj._myClass__myFunc()

Output:

Hello, World!

Use of Name Mangling in Function Overriding

Using inheritance, you can override the base class (parent class) function with a derived class (child class) function.

You can write a function with the same name in the parent as well as in the child’s class.

To avoid this ambiguity, you can add __ (double underscore) in front of the function name. With the Name Mangling mechanism, both the function will be renamed as below.

Name Mangling in the base class:

_<base_class_name>__<function_name>

Name Mangling in the derived class:

_<derived_class_name>__<function_name>

Now you can distinguish override function.

Function overriding without Name Managing.

class baseClass:
  def myFunc(self):
    print("I'm a parent.")

class derivedClass(baseClass):
  def myFunc(self):
    print("I'm a child.")

obj=derivedClass()
obj.myFunc()

Output:

I'm a child.

Even though myFunc() is defined in the base and derived class, the object of the derived class always calls the method from a derived class.

Function overriding with Name Mangling

class baseClass:
  def __myFunc(self):
    print("I'm a parent.")

class derivedClass(baseClass):
  def __myFunc(self):
    print("I'm a child.")

obj=derivedClass()
 
obj._derivedClass__myFunc()
obj._baseClass__myFunc()

Output:

I'm a child.
I'm a Parent.

Now you can call the same method in the base class as well as in the derived class using the Name Mangling mechanism.

Summary

Some points to be remembered.

  • Name mangling concept applies when the attribute is prefixed with __ (double underscores).
  • If the attribute is prefixed with _ (single underscore), it will work as normal attribute.
  • As a part of name mangling, attribute name will be changed to _<class_name><atrribute>. This format is used by a class object to access the attribute outside of the class.
  • Using name mangling we can access the members outside of the class. This means name mangling is closest to making members private, but it is not the exact way of making members private.

This concept is very important and was asked in many of the interviews. Check Name Mangling question asked in PwC interview round for Python developer.

This is all about Python Name Mangling. Any doubt? Let’s connect by writing in the comment. I will reply to every question.

Happy Pythoning!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    rajeev
    December 1, 2020 at 7:48 pm

    This is an amazing concept and Explanation. Kudos to you ..!

    • Reply
      Aniruddha Chaudhari
      December 1, 2020 at 8:32 pm

      Thanks, Rajeev! I’m glad you like it.

  • Reply
    Komal Verma
    September 26, 2021 at 10:47 pm

    Explained greatly…
    Thank you, Aniruddha.

    • Reply
      Aniruddha Chaudhari
      September 29, 2021 at 8:36 am

      You’re welcome! I’m glad you like it.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard