简体   繁体   中英

How to overload the subscript operator with swig Python

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

I have overloaded the subscript operator in C++ such that foos["Key Name"] will search through the vector for a Foo object with key matching "Key Name" (where foos is a std::vector<Foo> ).

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

Any tips on how to make SWIG recognize the subscript operator and overload it in Python? I am a little surprised that I couldn't find examples of people doing this online. I guess most people just use a std::map and have SWIG convert it to a Python dict .

In straight Python, if you want to overload the subscript operator, you would create a __getitem__ and __setitem__ class method. 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

So if you want to have C++ handle this, my very best guess (no, I haven't verified this) is that you would create a __getitem__ and __setitem__ in C++. You can either do this directly in your C++ code, or use the %extend directive within SWIG to call off to your C++ [] operator.

Python indexers are __getitem__ and __setitem__ methods.

See here on how to implement them.

Or you may use %extend clause in more modern SWIG.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM