Python代码中的SwigPyObject和JSON通信
问题描述:
介绍。 我有一个C++应用程序,我使用SWIG来启动GetObjects
和PutObjects
在python代码中定义的方法。 GetObjects
方法打开JSON格式的文件,从那里获取对象并将它们返回给C++应用程序。虽然PutObjects
方法从C++应用程序获取对象,但打开JSON格式化文件进行写入并将其存储在那里。Python代码中的SwigPyObject和JSON通信
代码很常见,它使用MyJSONDecode和MyJSONEncode函数在python对象和json字典之间进行交互。
现在的问题。 Swig将MyObject
C++类转换为位于abc
模块中的称为MyObject
的python类。我使用import abc
声明在代码中使用它,如abc.MyObject()
。 abc.MyObject
是SwigPyObject
,它没有字典本身(__dict__
成员)。
所以我不能遍历MyObject.__dict__
里面的MyJSONEncode函数来建立一个字典,应该由该函数返回,因此创建一个JSON格式。
但MyObject有属性,例如url或name等等。我如何迭代属性?
如果需要,我会为您提供代码。请让我知道。总的来说,我希望我的问题能够得到理解。
等待一种回应:)
答
您应该能够使用“目录”功能获取对象的属性列表。
这里是例子抓住所有非功能用户创建的属性(称为“属性”):
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))]