I have a class (PlayerList) that contains Player objects (or subclasses) by inheriting from list builtin. I want each of the Player objects to use the container's attribute true_dice. The problem is that for testing purposes I need each of the players to have the ability to use their own as well, if they are not part of a PlayerList
class PlayerList(list):
def __init__(plist):
# plist is a list of Player objects
self.true_dice = [0,0,0,0]
super().__init__(plist)
class Player:
def __init__():
self.true_dice = "<Magical code that gets containers true_dice>"
def turn(self):
"..."
self.true_dice[2] = 1 # Modify true_dice should modify PlayerList's aswell
What is the pythonic way to achieve this? A google search turns up no results.
I was thinking perhaps overriding __getattribute__ would work, but then I would have to store a reference to the PlayerList in the class, and that is a very tightly coupled solution:
class Player:
...
def __getattribute__(self, attrname):
if attrname=="true_dice":
return player_list_reference.true_dice # Defined in __init__
else:
return self.__dict__[attrname]
Or perhaps I could run an update function every time a member of the 'PlayerList' changes its true_dice attribute. This would separate concerns rather well...
Please comment any and all requests for edits.
Player, using thePlayerListattribute, or falling back to (or preferring?) thePlayer's own attribute?player_list_reference? Is this some global attribute, a placeholder for something to be defined, or a mistyped attribute ofPlayer?