我一直在使用python几年,但对于复杂的面向对象编程并不多,我很少使用字典作为结构。对于这个应用程序,我正在尝试在地图上建立一个地理位置定位点的数据库。
因此,我想创建一个能够访问二维字典结构并执行各种方法的容器类。为了可用性和可读性,我正在尝试实现各种容器方法,但是我很难添加类功能。
我的容器类的片段
# Python standard libraries
from collections import defaultdict
from GeoWayPt import *
#===========================================================================
class GeoWayPtData():
""" Geodetic waypoint data container """
# Nested dictionary structure for equipment/waypoints
def equip_dict(self): return defaultdict(self.waypt_dict)
def waypt_dict(self): return GeoWayPt
def __init__(self):
""" Constructor """
#
self.AvailEquipIndex = 0
# Nested dictionary of equipment with waypoints
#
# First key for each equipment.
# Second key for each waypoint.
# [EquipNum][WayptNum]
self.dictWayPts = defaultdict(self.equip_dict)
我不确定如何实现 iter 和下一个方法,以便在下面的测试脚本中实现循环功能。
我的数据类的一部分
class GeoWayPt():
""" Geodetic waypoint container class """
def __init__(self):
""" Constructor """
# Equipment ID (integer, starting at 0)
self.ID = 0
# Equipment class (string description)
self.EquipClassStr = ''
我的测试脚本
from GeoWayPt import *
from GeoWayPtData import *
# 2-D data structure
data = GeoWayPtData()
waypt = GeoWayPt()
waypt.ID = 0
waypt.EquipClassStr = "foo"
# Add equipment 0
data.AddEquip(waypt)
waypt = GeoWayPt()
waypt.ID = 0
waypt.EquipClassStr = "bar"
# Add waypoint to equipment 0
data.AddWayPt(0, waypt)
waypt = GeoWayPt()
waypt.ID = 1
waypt.EquipClassStr = "can"
# Add equipment 1
data.AddEquip(waypt)
waypt = GeoWayPt()
waypt.ID = 1
waypt.EquipClassStr = "haz"
# Add waypoint to equipment 1
data.AddWayPt(1, waypt)
waypt = GeoWayPt()
waypt.ID = 1
waypt.EquipClassStr = "sum"
# Add another waypoint to equipment 1
data.AddWayPt(1, waypt)
# Functionality I'd like:
for equip in data:
for waypt in equip:
print waypt.ID, waypt.EquipClassStr
答案 0 :(得分:1)
不是试图支持GeoWayPtData中的迭代,而是迭代GeoWayPtData中的defaultdict可能更容易:
for equip in data.dictWayPts.itervalues():
for waypt in equip.itervalues():
print waypt.ID, waypt.EquipClassStr
当然,您还可以通过添加产生航路点的__iter__
将此功能添加到GeoWayPtData:
def __iter__(self):
for equip in self.dictWayPts.itervalues():
for waypt in equip.itervalues():
yield waypt
然后你可以这样做:
for waypt in data:
print waypt.ID, waypt.EquipClassStr