如何在Python中处理类似IDL结构的数据?

1 投票
1 回答
908 浏览
提问于 2025-04-18 03:00

我正在把一些代码从IDL转换成Python。在IDL中,有大约50个变量被放在一个结构体的结构体里。

values = { struct1: {a = 1, b = 2}, struct2: {a = 3, b = 4} ... etc }

这些数据可以这样访问:

print, values.struct1.a
# 1

有没有简单的方法在Python中做到这一点,同时还能在类的值里面有方法来操作内部的类?比如说,有一个setValues的方法可以改变struct1或struct2中的值?我希望能有这样的东西:

class values:
    def __init__(self):
         self.struct1 = self.struct1()
         self.struct2 = self.struct2()

    class struct1:
         def __init__(self):
             self.a = 1
             self.b = 2
    class struct2: 
         def __init__(self):
             self.c = 3
             self.d = 4

    def setValues(self, **kwargs):
        for key,value in kwargs.items():
             setattr(self, key, value)
        return

这样我就可以执行以下代码:

st = values()
st.setValue(struct1.a = 2.0, struct2.a = 5.0)
print, st.struct1.a , st.struct2.a
# 2.0
# 5.0

但是我遇到了以下错误:

AttributeError: values instance has no attribute 'struct1'

我对Python还很陌生,想知道有没有人能提供一些更好的方法来创建嵌套类,并且让方法可以作用于所有嵌套的类。

1 个回答

0

代码如下:

class values:

    class struct1:
         def __init__(self):
             self.a = 1
             self.b = 2

    class struct2: 
         def __init__(self):
             self.c = 3
             self.d = 4

    def __init__(self):
         self.struct1 = self.struct1()
         self.struct2 = self.struct2()

    def setValue(self, **kwargs):
        for key, value in kwargs.items():
            try:
                getattr(self.struct1, key)
            except AttributeError:
                # self.struct1 don't have any attribute which name is the value of 'key'.
                pass
            else:
                setattr(self.struct1, key, value)

            try:
                getattr(self.struct2, key)
            except AttributeError:
                # self.struct2 don't have any attribute which name is the value of 'key'.
                pass
            else:
                setattr(self.struct2, key, value)

你可以:

>>> st = values()
>>> st.struct1.a = 10
>>> st.struct2.c = 20
>>> print(st.struct1.a)
>>> 10
>>> print(st.struct2.c)
>>> 20
>>> st.setValue(b=20, a=100, d=50, c=60)
>>> print(st.struct1.a)
>>> print(st.struct1.b)
>>> print(st.struct2.c)
>>> print(st.struct2.d)
>>> 100
>>> 20
>>> 60
>>> 50

补充说明:在你最开始的问题中,你写的是 __init,其实应该是 __init__,还有:

self.struct1 = self.struct1()
self.struct1 = self.struct2()   # Here you was redefining self.struct1

我改成了:

self.struct1 = self.struct1()
self.struct2 = self.struct2()

撰写回答