Code Explanation:
1. Defining the Class
class A:
Creates a class named A
By default, it inherits from object
๐น 2. Defining a Method in the Class
def f(self):
return 1
f is an instance method
When called normally, it returns 1
Stored in the class namespace, not inside objects
๐น 3. Creating an Object of the Class
a = A()
Creates an instance a
At this point:
a does not have its own f
Method f is accessed from the class
๐น 4. Assigning a New Attribute to the Instance
a.f = lambda: 5
Creates an instance attribute named f
This overrides (shadows) the class method f
lambda: 5 is a function that returns 5
Stored in a.__dict__
๐ Important:
Instance attributes have higher priority than class attributes.
๐น 5. Calling a.f()
print(a.f())
Attribute lookup order:
Python checks a.__dict__ → finds f
Class method A.f is ignored
Calls the lambda function
Lambda returns 5
✅ Final Output
5

0 Comments:
Post a Comment