Code Explanation:
1. Defining the class
class Test:
This line defines a class named Test.
2. Defining an instance method
def f(self):
f is an instance method.
Normally, t.f refers to this method.
3. Assigning to the same name inside the method
self.f = 5
This line creates an instance attribute named f.
It overwrites (shadows) the method f for this specific object.
After this line runs:
t.__dict__ = {'f': 5}
4. Returning a value
return 1
The method returns the integer 1.
5. Creating an instance
t = Test()
An object t of class Test is created.
At this moment, t.f still refers to the method.
6. Calling and accessing in print
print(t.f(), t.f)
Let’s evaluate left to right ๐
๐น First: t.f()
Python finds f as a method in class Test.
The method is called.
Inside the method:
self.f = 5 creates an instance attribute.
1 is returned.
So t.f() evaluates to 1.
๐น Second: t.f
Python now looks for f in the instance first.
It finds f = 5 in t.__dict__.
The method is no longer visible via t.f.
So t.f evaluates to 5.
✅ Final Output
1 5

0 Comments:
Post a Comment