riccio777 riccio777 - 3 months ago 23
Python Question

Python: Sub attribute in a class

It's probably a silly question, but I am stuck here. In Python I have created a class Match, with some attributes like my_match.goals, my_match.yellow_cards, etc.
I would like every match to also have some of the same attributes but restricted to the first half of the game.
Ideally, my first thought would be a kind of sub attribute, something like

my_match.half_time.goals


but of course it doesn't work.

My question is: what would be the best data structure for such a necessity and how would I implement it? I don't think a subclass would be a good idea, because I want the same instance to be able to describe half time and full time.
Thank you!

Answer

In order to avoid using or creating another class, you can use namedtuples objects. Named tuple instances can be referenced using object like variable deferencing or the standard tuple syntax.

from collections import namedtuple
HalfTime = namedtuple('Halftime', 'goals yellow_cards')
my_match.half_time = HalfTime(4, 5)
my_match.half_time.goals
>>> 4
my_match.half_time.yellow_cards
>>> 5

If you want to update your values

my_match.half_time = my_match.half_time._replace(goals=10)