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()
If
Family
is supposed to containAgent
objects, why does it inherit fromAgent
? Regardless, you never initialized the parentAgent
object in theFamily
class's__init__
, and according to your edit theget_money
method is contained in theAgent
class, soFamily
objects don't have aget_money
method. To access that, you would need to first access aFamily
object'smembers
dictionary, then use a key to access the desiredAgent
object, then access that object'sget_money
method.