How to overload index operator using swig python

I have a class that contains std::vector<Foo>, where Foois the class containing the key, value, comment, etc. Please note that there is a reason why I use a vector, not a dictionary.

I overloaded the index operator in C ++ foos["Key Name"]to do a vector search for the Foo object with the key matching "Key Name" (where foos- std::vector<Foo>).

I use SWIG to create a Python wrapper for my library, and I really want this subscript operator to expand in Python. In other words, I want to be able to use foos["Key Name"]to search for objects in a vector in Python.

Any tips on how to get SWIG to recognize the index operator and overload it in Python? I am a little surprised that I could not find examples of people who do this on the Internet. I think most people just use it std::map, and SWIG converts it to Python dict.

+3
source share
2 answers

In direct Python, if you want to overload the index operator, you must create a class method __getitem__and __setitem__. As a simple example:

class MyClass(object):
    def __init__(self):
        self.storage = {}

    def __getitem__(self, key):
        return self.storage[key]

    def __setitem__(self, key, value):
        self.storage[key] = value

, , ++ , (, ) , __getitem__ __setitem__ ++. ++ %extend SWIG ++ [].

+5

Python - __getitem__ __setitem__.

, .

%extend SWIG.

+2

All Articles