En Wed, 13 Feb 2008 05:34:43 -0200, Mike D <[EMAIL PROTECTED]> escribió:
> I have a simple requirement: A user belongs to groups and groups contain > items. > > Based on user/group I want to display items. > Based on user I want to display groups. > > What would be the best method of implementing this? A dictionary of > objects? > > I'd usually just use a database but I feel it's quite unnessacary and > its a > scenario I'd like to know the solution for. Assuming there is no inherent ordering in groups nor items, I'd use a set for both. py> class Group(object): ... def __init__(self, name): ... self.name = name ... self.items = set() ... def __repr__(self): ... return '%s(%r)' % (self.__class__.__name__, self.name) ... py> class User(object): ... def __init__(self, name): ... self.name = name ... self.groups = set() ... def __repr__(self): ... return '%s(%r)' % (self.__class__.__name__, self.name) ... def all_items(self): ... result = set() ... for group in self.groups: ... result.update(group.items) ... return result ... py> gA = Group('A') py> gA.items.add('Item One') py> gA.items.add('Item Two') py> gB = Group('B') py> gB.items.update(['Item Three','Item Four','Item Five']) py> gC = Group('C') py> gC.items.update(['Item Six','Item Seven']) py> py> piluso = User('piluso') py> piluso.groups.add(gA) py> piluso.groups.add(gB) py> coquito = User('coquito') py> coquito.groups.add(gB) py> coquito.groups.add(gC) py> py> print piluso, piluso.groups User('piluso') set([Group('A'), Group('B')]) py> print coquito, coquito.groups User('coquito') set([Group('B'), Group('C')]) py> print "group B items:", gB.items group B items: set(['Item Three', 'Item Five', 'Item Four']) py> print "groups B and C items:", gB.items | gC.items groups B and C items: set(['Item Seven', 'Item Six', 'Item Three ', 'Item Four', 'Item Five']) py> print "coquito's items:", coquito.all_items() coquito's items: set(['Item Seven', 'Item Six', 'Item Three', 'I tem Four', 'Item Five']) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list