Code Explanation:
1. Class Definition
class A:
This line defines a class named A.
2. Method Definition
def show(self):
print("A")
show is an instance method of class A.
self refers to the object that calls the method.
When called normally, this method prints "A".
3. Object Creation
obj1 = A()
obj2 = A()
Two separate objects (obj1 and obj2) are created from class A.
Both objects initially have access to the same show() method defined in class A.
4. Method Overriding for a Single Object
obj1.show = lambda: print("B")
A lambda function is assigned to obj1.show.
This overrides the show method only for obj1, not for the class or other objects.
Now:
obj1.show() prints "B"
obj2.show() still refers to the original class method.
5. Calling show() on obj1
obj1.show()
Calls the overridden method attached to obj1.
Output:
B
6. Calling show() on obj2
obj2.show()
Calls the original show() method from class A.
Output:
A
7. Final Output
B
A


0 Comments:
Post a Comment