Understanding inheritance in practice. Printing values of an instance

58 views Asked by At

I have a class of Agents with a working __str__ method. I have a class of Family(Agents). The Family is structured as a dictionary with the Agent ID as key. After allocating agents to families, I iterate over my_families: When I print members.keys(), I get the correct keys. When I print members.values(), I get a list of instances

But, I cannot access the values themselves inside the instances. When I try to use a method get_money() I get an answer that Family class does not have that method. Any help?

for family in my_families:
    print family.members.values()

Thanks

Providing more information. Family class

class Family(agents.Agent):
"""
Class for a set of agents
"""
    def __init__(self, family_ID):
        self.family_ID = family_ID
        # _members stores agent set members in a dictionary keyed by ID
        self.members = {}

    def add_agent(self, agent):
        "Adds a new agent to the set."
        self.members[agent.get_ID()] = agent

Class of agents

class Agent():
    "Class for agent objects."
    def __init__(self, ID, qualification, money):
        # self._ID is unique ID number used to track each person agent.
        self.ID = ID
        self.qualification = qualification
        self.money = money

    def get_ID(self):
        return self.ID

    def get_qual(self):
        return self.qualification

    def get_money(self):
        return self.money

    def __str__(self):
    return 'Agent Id: %d, Agent Balance: %d.2, Years of Study: %d ' (self.ID, self.money, self.qualification)

#Allocating agents to families

def allocate_to_family(agents, families):
    dummy_agent_index = len(agents)
    for family in families:
        dummy_family_size = random.randrange(1, 5)
        store = dummy_family_size
        while dummy_family_size > 0 and dummy_agent_index >= 0 and (dummy_agent_index - dummy_family_size) > 0:
            family.add_agent(agents[dummy_agent_index - dummy_family_size])
            dummy_family_size -= 1
        dummy_agent_index -= store

Finally the printing example that gets me instance objects but not their values

for family in my_families:
    print family.members.values()
1

There are 1 answers

1
TigerhawkT3 On BEST ANSWER

If Family is supposed to contain Agent objects, why does it inherit from Agent? Regardless, you never initialized the parent Agent object in the Family class's __init__, and according to your edit the get_money method is contained in the Agent class, so Family objects don't have a get_money method. To access that, you would need to first access a Family object's members dictionary, then use a key to access the desired Agent object, then access that object's get_money method.