Items inheriting attributes from its container?

Kreso kkumerNOTTHIS at
Sun Aug 23 00:49:22 CEST 2009

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'
print item.color

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.

class Player:
    """Class for items"""

    def __init__(self, playerdata, team): = playerdata
        for key in team.__dict__:
            setattr(self, key, team.__dict__[key])

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))

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


More information about the Python-list mailing list