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... 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
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you!, if i were to do that, would I have to declare my structure as a MyDict?
No, thats just an example. Chose any class name that suits your needs
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()?
of course you must use structure = MyDict() otherwise it won't work
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.