Feb-27-2023, 09:25 AM
(This post was last modified: Feb-27-2023, 09:25 AM by Gribouillis.)
Using a metaclass, it is easy to distort the class syntax to produce just a dictionary. This could be especially useful to create dictionaries of functions
class just_a_dict: def __new__(cls, name, bases, dic): # remove keys ending with two underscores return {k: v for k, v in dic.items() if not k.endswith('__')} class somedict(metaclass=just_a_dict): data = (8, 7, 3) def foo(): print('foo was called') def spam(x, y): print(f'spam said {x + y}') print('type of somedict is', type(somedict)) print(somedict) somedict['foo']() somedict['spam'](10, 100)
Output:type of somedict is <class 'dict'>
{'data': (8, 7, 3), 'foo': <function somedict.foo at 0x7fd44b27e0e0>, 'spam': <function somedict.spam at 0x7fd44b27e170>}
foo was called
spam said 110