2

I have a class that contains a static dictionary:

class MyClass:
    my_dict = {}
    def __init__(self, name):
        self.name = name
        MyClass.my_dict[self.name] = []
    def __call__(self, data):
        MyClass.my_dict[self.name].append(data)

Whenever I want to update the dictionary, I have to use MyClass.my_dict[key], but I'd like the class itself to support item assignment so I can just use MyClass[key] to do the same thing. Is there a way to do this? I'm using Python 2.7.

John Thompson
  • 1,674
  • 1
  • 20
  • 35

1 Answers1

5

So, here's what I ended up doing:

class MyClassType(type):
    my_dict = {}
    def __getitem__(cls, key):
        return cls.my_dict[key]
    def __setitem__(cls, key, value):
        cls.my_dict[key] = value
    def __str__(cls):
        return cls.my_dict.__str__()
    def iteritems(cls):
        return cls.my_dict.iteritems()

class MyClass(object):
    __metaclass__ = MyClassType
    def __init__(self, name):
        self.name = name
        MyClass[self.name] = []
    def __call__(self, data):
        MyClass[self.name].append(data)
John Thompson
  • 1,674
  • 1
  • 20
  • 35
  • Hi, I am trying to use your code but I does not work..even with putting the metaclass=MyClassType as a parameter of MyClass – Francois Sep 30 '22 at 08:26