如何将嵌套的namedtuple映射到具有嵌套"数据字段的类#34;?

时间:2018-06-18 14:10:17

标签: python-2.7 namedtuple

我有一个Python类class PointStamped,它允许定义嵌套的"数据字段" (例如p.header.frame_id="test",见下文)。我想将相应的namedtuple PointStampedNamedtuple = namedtuple('PointStamped', 'Header Point')的字段映射到此类。这可以明确地完成(如本问题末尾的示例)。但是,我更愿意实现映射,而无需将namedtuples字段值分配给类"数据字段"明确。我在考虑类似下面的伪代码:

# PSEUDO CODE
def map(namedtuple):
    """
    Maps the namedtuple keys and values to corresponding class "data fields".
    Takes namedtuple as argument, returns instance with accordingly initialized "data field" values.
    """
    for every key in namedtuple:
        get key value
        assign key value to corresponding class "data field"

# which could be used somehow like...
p = convert(PointStampedNamedtuple(header=(seq=0, stamp=(0, 0), frame_id="test"),
                                   point=(x=2.0, y=0.0, z=0.0))

# with "data field" values of `p` assigned as follows

print(p)
# header: 
#   seq: 0
#   stamp: 
#     secs: 0
#     nsecs:         0
#   frame_id: test
# point: 
#   x: 2.0
#   y: 0.0
#   z: 0.0

这怎么可能最简单?

该类允许定义数据,例如如下:

>>> from geometry_msgs.msg import PointStamped
>>> p = PointStamped()
>>> p.header.frame_id = "test"
>>> p.point.x = 2.0

相应的类导致:

>>> print(p)
header: 
  seq: 0
  stamp: 
    secs: 0
    nsecs:         0
  frame_id: test
point: 
  x: 2.0
  y: 0.0
  z: 0.0

类构造函数如下所示:

class PointStamped(genpy.Message):
  ...

  def __init__(self, *args, **kwds):
    """
    ...

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(PointStamped, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.header is None:
        self.header = std_msgs.msg.Header()
      if self.point is None:
        self.point = geometry_msgs.msg.Point()
    else:
      self.header = std_msgs.msg.Header()
      self.point = geometry_msgs.msg.Point()

namedpuples PointStampedNamedtuple = namedtuple('point_stamped', 'header point')字段名称headerpoint的类型名为small header = namedtuple('header', 'seq stamp frame_id')stamp映射到字段名称secs和{{ 1}})和nsecs本身。

可以像下面那样将namedtuple显式映射到类(但我正在寻找一些更容易的,"隐式"映射实现):

Point = namedtuple('point', 'x y z')

0 个答案:

没有答案