Google News
logo
Python Program to Delete an Object
To delete an object in Python, you can use the `del` keyword followed by the object name. Here is an example program that demonstrates how to delete an object :
Program :
# Define a class
class MyClass:
    def __init__(self, x):
        self.x = x

# Create an object of the class
myObj = MyClass(5)

# Print the value of the object's property
print(myObj.x)  # Output: 5

# Delete the object
del myObj

# Try to print the value of the object's property (will result in an error)
print(myObj.x)  # Output: NameError: name 'myObj' is not defined
In this program, we define a class `MyClass` with an `__init__()` method that initializes an object's property `x`. We then create an object `myObj` of the class with the value `5` for the property `x`.

We print the value of `myObj.x`, which is `5`. We then delete the object using the `del` keyword followed by the object name `myObj`.

Finally, we try to print the value of `myObj.x`, which results in a `NameError` since `myObj` no longer exists.