Create a python object that can be accessed with square brackets

后端 未结 2 1718
终归单人心
终归单人心 2020-12-29 01:28

I would like to create a new class that acts as a special type of container for objects, and can be accessed using square brackets.

For example, suppose I have a cla

2条回答
  •  囚心锁ツ
    2020-12-29 02:10

    Python's standard objects have a series of methods named __something__ which are mostly used to allow you to create objects that hook into an API in the language. For instance __getitem__ and __setitem__ are methods that are called for getting or setting values with [] notation. There is an example of how to create something that looks like a subclass of the Python dictionary here: https://github.com/wavetossed/mcdict

    Note that it does not actually subclass dictionary and also, it has an update method. Both of these are necessary if you want your class to properly masquerade as a Python dictionary.

提交回复
热议问题