1

So I have a dictionary on python:

structure = dict()

and I would like to know how I could achieve something like that:

structure.my_func(parameters);

Where my_func is my custom function.

So I in some way extend it's functionality, I knew we could do that in javascript with prototypes.

Is it possible on python? If yes, how?

Thanks in advance.

4
  • You can define a subclass of the python dict class. This subclass can then have your custom attributes and methods. Commented Jun 11, 2020 at 21:45
  • @DavidWierichs would you have an example? I'm really not familiar with python...
    – Alex
    Commented Jun 11, 2020 at 21:45
  • Simply extend dict: class my_dict(dict): Commented Jun 11, 2020 at 21:46
  • I think this is very well web-searchable. If you run into concrete problems while realising your idea, post them here. Commented Jun 11, 2020 at 21:46

2 Answers 2

5

As stated in the comments, define a subclass of the python dict class:

class MyDict(dict):
    def __init__(self):
        super().__init__()

    def my_method(self):
        # do what you want here
4
  • Thank you!, if i were to do that, would I have to declare my structure as a MyDict?
    – Alex
    Commented Jun 11, 2020 at 21:48
  • No, thats just an example. Chose any class name that suits your needs Commented Jun 11, 2020 at 21:49
  • let's say I wanted to keep my statement as structure = dict() would I be able to do structure.my_method(params) or would I have to change my declaration to structure = MyDict()?
    – Alex
    Commented Jun 11, 2020 at 21:50
  • 1
    of course you must use structure = MyDict() otherwise it won't work Commented Jun 11, 2020 at 21:51
3

Python provides the collections.abc module to help a programmer to define a custom container. You should use collection.abc.Mapping for a read only container, or collection.abc.MutableMapping for a mutable one.

Depending on the use case, it can be simpler to inherit from those abstract base classes than directly from a true dict.

Not the answer you're looking for? Browse other questions tagged or ask your own question.