Code Explanation:
1. Defining the Class
class C:
A class named C is defined.
It will create objects that have an attribute x.
2. Constructor Method (__init__)
def __init__(self):
self.x = 5
The constructor runs when an object is created.
It creates an instance attribute x and sets it to 5.
So after object creation:
c.x = 5
3. Creating an Object
c = C()
An object c of class C is created.
The constructor assigns c.x = 5.
4. Deleting the Attribute
del c.x
The del keyword removes the attribute x from the object c.
Now c no longer has an attribute named x.
After this:
c.__dict__ = {}
5. Trying to Access Deleted Attribute
print(c.x)
Python tries to find attribute x inside c.
It does not exist anymore.
Python raises an error:
AttributeError: 'C' object has no attribute 'x'
Final Result
Output before crash:
Nothing is printed.
Error:
AttributeError: 'C' object has no attribute 'x'


0 Comments:
Post a Comment