Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (12.7k points)

I will be using  __delitem__  with a class-level variable. I just need to know is there anyway, so that I can get the class object to support __delitem__?

class Foo(object):

    _instances = {}

    def __init__(self, my_str):

        n = len(self._instances) + 1

        self._instances[my_str] = n

        print "Now up to {} instances".format(n)

    @classmethod

    def __delitem__(cls, my_str):

        del cls._instances[my_str]

abcd = Foo('abcd')

defg = Foo('defg')

print "Deleting via instance..."

del abcd['abcd']

print "Done!\n"

print "Deleting via class object..."

del Foo['defg']

print "You'll never get here because of a TypeError: 'type' object does not support item deletion"

1 Answer

0 votes
by (26.4k points)

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...