English

What do you mean by name mangling? Support your answer with a relevant example.

Advertisements
Advertisements

Question

What do you mean by name mangling? Support your answer with a relevant example.

Code Writing
Short Answer
Advertisements

Solution

Name mangling is Python's limited mechanism for hiding class attributes. An attribute beginning with two underscores and not ending with two underscores is internally renamed by prefixing it with _ClassName.

class Test:
    def __init__(self):
        self.__marks = 95  # Name-mangled attribute

    def display(self):
        print(self.__marks)


t1 = Test()
t1.display()
print(t1._Test__marks)  # Access using mangled name
95
95

Here, __marks is internally stored as _Test__marks. Name mangling discourages direct access; it does not provide absolute privacy.

shaalaa.com
  Is there an error in this question or solution?
Chapter 3: Classes in Python - EXERCISE [Page 62]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 3 Classes in Python
EXERCISE | Q 11. | Page 62
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×