Python will calls __delitem__ method of the obj class, when you type del obj[key]. So del obg[key] results in type(obj).__delitem__(obj, key).
Which means, type(Foo).__delitem__(Foo, 'abcd'). type(Foo) is type, and the type.__delitem__ is not defined, in your case. Here, You actually need to change the type of Foo, since you can't modify type.
You can achieve by defining a new metaclass, which is a subclass of type, then commanding python to use your new metaclass to create Foo class
class ClassMapping(type):
def __new__(cls, name, bases, dct):
t = type.__new__(cls, name, bases, dct)
t._instances = {}
return t
def __delitem__(cls, my_str):
del cls._instances[my_str]
class Foo(object):
__metaclass__ = ClassMapping
def __init__(self, my_str):
n = len(Foo._instances) + 1
Foo._instances[my_str] = n
print "Now up to {} instances".format(n)
When you are changing the metaclass of Foo from type to ClassMapping, it provides "Foo" with
1. A class variable "_instance" actually refers to a dictionary
2. It also provides "__delitem__" method, which removes arguments from "_instances"
Want to become a Python Expert? Come and join: Python course