我听说并读到,使用C语言定义的类结构很容易定义大量信息(参见下面的C代码)。
我想用Python定义类似的方式。我对代码不太感兴趣,而且我是Python的新学习者组。
有关哪种方式可以轻松定义的任何建议?走dict
很好,但class
最好。
下面的C代码示例(我还有其他类似的结构和信息):
typedef struct
{
U16 ID;
S8 Name[32];
S8 Description[96];
S8 Units[16];
enum eType Type;
F32 Scaling;
F32 Offset;
BOOL Writeable;
} sDataInfo;
/* ID, Name, Description, Unit, Type, Scaling, Offset, Writable */
sDataInfo data_items[] =
{
0x0202, "dtc_num_of_faults_", "Number of DTCs", "", u8, 1, 0, FALSE,
0x2007, "FlBodyVertLocSel_A_Meas_", "FL Vertical Acceleration", "m/s^2", s16, 0.05, 0, FALSE,
0x2008, "FrBodyVertLocSel_A_Meas_", "FR Vertical Acceleration", "m/s^2", s16, 0.05, 0, FALSE,
0x2022, "RlBodyVertLocSel_A_Meas_", "RL Vertical Acceleration", "m/s^2", s16, 0.05, 0, FALSE
}
重要的是要知道每个代码都可以在Python中更改。在任何在线链中都没有回答上述问题。
并期待一些例子。
答案 0 :(得分:1)
正如我在评论中所说的那样,我不确定你想要什么...但是这里有一个猜测:
from pprint import pprint
import sys
def sprintf(format, *args):
return format % args
def _attributes_from_dict(d):
self = d.pop('self')
for n, v in d.items():
setattr(self, n, v)
class DataInfo(object):
fieldnames = 'id, name, description, units, type, scaling, offset, writeable'.split(', ')
def __init__(self, id, name, description, units, type, scaling, offset, writeable):
_attributes_from_dict(locals())
def __repr__(self): # optional
values = tuple(getattr(self, fieldname) for fieldname in self.fieldnames)
id = values[0]
remainder = ', '.join(map(repr, values[1:]))
return sprintf('%s(0x%04x, %s)', self.__class__.__name__, id, remainder)
u8, s16 = 0, 1 # enum eType names and values
data_items = [
DataInfo(*args) for args in [
(0x0202, "dtc_num_of_faults_", "Number of DTCs", "", u8, 1, 0, False),
(0x2007, "FlBodyVertLocSel_A_Meas_", "FL Vertical Acceleration", "m/s^2", s16, 0.05, 0, False),
(0x2008, "FrBodyVertLocSel_A_Meas_", "FR Vertical Acceleration", "m/s^2", s16, 0.05, 0, False),
(0x2022, "RlBodyVertLocSel_A_Meas_", "RL Vertical Acceleration", "m/s^2", s16, 0.05, 0, False),
]
]
pprint(data_items)
输出:
[DataInfo(0x0202, 'dtc_num_of_faults_', 'Number of DTCs', '', 0, 1, 0, False),
DataInfo(0x2007, 'FlBodyVertLocSel_A_Meas_', 'FL Vertical Acceleration', 'm/s^2', 1, 0.05, 0, False),
DataInfo(0x2008, 'FrBodyVertLocSel_A_Meas_', 'FR Vertical Acceleration', 'm/s^2', 1, 0.05, 0, False),
DataInfo(0x2022, 'RlBodyVertLocSel_A_Meas_', 'RL Vertical Acceleration', 'm/s^2', 1, 0.05, 0, False)]