del — Advanced Playground
Deletes a variable, list item, dictionary entry, or object attribute
Python Playground
class ProtectedAttribute:
def __set_name__(self, owner, name):
self.name = name
self.private_name = f"_{name}"
def __get__(self, obj, objtype=None):
return getattr(obj, self.private_name, None)
def __set__(self, obj, value):
setattr(obj, self.private_name, value)
def __delete__(self, obj):
raise AttributeError(f"Cannot delete {self.name}")
class User:
name = ProtectedAttribute()
email = ProtectedAttribute()
def __init__(self, name, email):
self.name = name
self.email = email
u = User("Alice", "alice@example.com")
print(f"Name: {u.name}")
try:
del u.name
except AttributeError as e:
print(f"Protected: {e}")
Output
Click "Run" to execute your code
Descriptors can implement __delete__ to control what happens when 'del obj.attr' is used. This enables read-only or protected attributes.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?