开发者

SwigPyObject and JSON communication inside python code

Intro. I have a C++ application, I use SWIG to launch GetObjects and PutObjects methods which are defined in python code. GetObjects method opens JSON format开发者_运维百科ed file, takes objects from there and returns back them to C++ application. While the PutObjects method gets objects from C++ application, opens JSON formated file for writing and stores them over there.

The code is pretty common and uses MyJSONDecode and MyJSONEncode functions to interact between python objects and json dictionaries.

Now the problem. Swig converts MyObject C++ class into python class called MyObject located in abc module. I use import abc statement to use it further in code like abc.MyObject(). abc.MyObject is a SwigPyObject and it does not have dictionary itself (__dict__ member).

So I can't iterate through MyObject.__dict__ inside MyJSONEncode function to build up a dictionary which should be returned by the function and therefore to create a JSON format.

But MyObject has properties, for example url or name and so on. How can I iterate through properties ?

If needed, I will provide you with code. Just let me know. Also I hope, in general, my problem is understood.

Waiting for kind response :)


You should be able to use the "dir" function to get a list of attributes of an object.

Here is example which grabs all non function user created attributes (called "properties"):

import inspect

class MyObject(object):
    def __init__(self):
        self.b = 1
        self.c = 'a'
    def func(self):
        pass

obj = MyObject()
# Get all the user created attributes for the object
attributes = [d for d in dir(obj)
              if not d.startswith('__')]
# Filter those to get the non functions
properties = [a for a in attributes
              if not inspect.ismethod(getattr(obj,a))]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜