0
0
Pythonprogramming~15 mins

Name mangling in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Name Mangling in Python
📖 Scenario: Imagine you are creating a simple class to store information about a secret agent. You want to keep the agent's real identity hidden inside the class so it cannot be accessed directly from outside.
🎯 Goal: You will create a class with a private attribute using name mangling, then access it safely through a method.
📋 What You'll Learn
Create a class called Agent with a private attribute
Use name mangling by prefixing the attribute name with double underscores
Add a method to return the private attribute value
Create an instance of the class and print the secret identity using the method
💡 Why This Matters
🌍 Real World
Name mangling helps protect sensitive data inside classes, like passwords or secret information, so it is not easily accessed or changed from outside.
💼 Career
Understanding name mangling is important for writing secure and well-encapsulated Python code, a key skill for software developers and engineers.
Progress0 / 4 steps
1
Create the Agent class with a private attribute
Create a class called Agent with a private attribute named __real_name set to the string 'James Bond' inside the __init__ method.
Python
Need a hint?

Use self.__real_name = 'James Bond' inside the __init__ method to create the private attribute.

2
Add a method to access the private attribute
Inside the Agent class, add a method called get_real_name that returns the value of the private attribute __real_name.
Python
Need a hint?

Define a method get_real_name that returns self.__real_name.

3
Create an instance of Agent
Create a variable called agent and assign it to a new instance of the Agent class.
Python
Need a hint?

Create an instance by writing agent = Agent().

4
Print the secret identity using the method
Use print to display the secret identity by calling the get_real_name method on the agent object.
Python
Need a hint?

Call agent.get_real_name() inside print() to show the secret name.