Code :
Explanation:
๐น 1. Importing methodcaller
from operator import methodcaller
✅ Explanation
methodcaller() is imported from Python's operator module.
It creates a function that calls a specific method on any object you pass to it.
Instead of calling a method directly, methodcaller stores the method name and calls it later.
Think of it like a remote control.
TV
▲
│
Remote
│
Press "Power"
│
TV Turns ON
Here,
Remote → methodcaller
Power Button → "upper"
TV → "python"
๐น 2. Creating a String
text = "python"
✅ Explanation
A string variable named text is created.
Current memory:
text
│
▼
"python"
๐น 3. Creating a Method Caller
upper = methodcaller("upper")
✅ Explanation
This line does not call the upper() method.
Instead, it creates a callable object that remembers:
Whenever someone gives me an object,
I'll call its upper() method.
Think of it like preparing a command.
Current memory:
upper
│
▼
Call upper() later
Nothing has executed yet.
๐น 4. What is Stored Inside upper?
Internally Python creates something similar to:
def upper(obj):
return obj.upper()
So,
upper = methodcaller("upper")
behaves almost like:
def upper(obj):
return obj.upper()
It is waiting for an object.
๐น 5. Calling the Function
upper(text)
✅ Explanation
Now Python passes:
text
to the stored function.
Internally:
text.upper()
gets executed.
Current value:
"python"
๐น 6. Executing upper()
Python now performs:
"python".upper()
The upper() string method converts every lowercase letter into uppercase.
Before:
python
After:
PYTHON
Notice:
The original string is not changed because strings are immutable.
๐น 7. Printing the Result
print(upper(text))
✅ Explanation
Python prints the returned value.
Output:
PYTHON
๐ฏ Final Output
PYTHON

0 Comments:
Post a Comment