I’ve been using python for a couple years on and off, but not much for complicated object oriented programming and I rarely use dictionaries as a structure. For this application I’m trying to build a database of geo-located waypoints on a map.
As such, I want to create a container class that is capable of accessing a 2-D dictionary structure and performing various methods. In the interest of usability and readability, I’m trying to implement the various container methods, but I’m having a hard time adding the class functionality.
A snippet of my container class
# 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)
I wasn’t sure how to implement the iter and next methods in order to achieve the looping functionality in the test script below.
Part of my data class
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 = ''
My test script
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
Instead of trying to support iteration in GeoWayPtData, it may be easier to iterate over the defaultdict in GeoWayPtData:
Of course you could also add this functionality to GeoWayPtData by adding an
__iter__that yields the waypoints:Then you could do this: