Items inheriting attributes from its container?

Stephen Fairchild somebody at somewhere.com
Sat Aug 22 19:46:26 EDT 2009


Kreso wrote:

> I would like to create a list-like container class so that, additionally
> to usual list methods, I could attach attributes to the container
> instances. However, I would like it so that the items contained in the
> particular instance of container somehow 'inherit' those attributes i.e.
> 
> cont = Container()
> cont.color = 'blue'
> cont.append(item)
> print item.color
> 'blue'
> 
> The example appended below does that, but with the restriction that
> container attributes must be set in the instantiation phase. This is
> actually fine for me at the moment because my objects are "read only", but
> I would like to hear about better solutions, with more flexibility,
> please.
> 
> 
> #-----8<----------------------------
> class Player:
>     """Class for items"""
> 
>     def __init__(self, playerdata, team):
>         self.data = playerdata
>         for key in team.__dict__:
>             setattr(self, key, team.__dict__[key])
>         return
> 
> 
> class Team(list):
>     """Class for containers"""
>     
>     def __init__(self, teamdata, playerdata):
>         for key in teamdata:
>             setattr(self, key, teamdata[key])
>         for item in playerdata:
>             self.append(Player(item, self))
>         return
>             
> 
> lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'}
> lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]]
> 
> lakers = Team(lakersdata, lakersplayers)
> 
> # This is fine:
> p1 = lakers[1]
> print p1.kitcolor
> 
> # However the following doesn't work:
> lakers.kitcolor = 'blue'
> print p1.kitcolor
> 
> #-----8<----------------------------

I hope this gives you some good ideas.

http://en.wikipedia.org/wiki/Join_(SQL)

I suspect you will be finding a use for the special __getattr__ method,
which is called when an attribute is not found. This can be used to search
on your set of joined objects. Your list of joined objects should be a
set() to prevent duplicates.
-- 
Stephen Fairchild



More information about the Python-list mailing list