I'm trying to create a Child class within a Person class, but am having trouble accessing the child object after creation, when more than one instance is created dynamically.
For example, I ask the user how many kids they have, and I then want to create an instance of the inner child class for each child they have, and be able to access that information later.
Here is some code that I have tried so far, which works for one child. But I can't figure out how to access the information if they have more than 1 child.
class Person:
def __init__(self, firstName, lastName, age):
self.firstName = firstName
self.lastName = lastName
self.age = age
self.numberOfChildren = 0
class Child:
def __init__(self, firstName, age):
self.firstName = firstName
self.age = age
def show(self):
print(self.firstName, self.age)
client = Person("Jake", "Blah", 31)
numberOfChildren = input("How many kids do you have?")
client.numberOfChildren = 2
for i in range(numberOfChildren):
firstName = input("What is the name of your child?")
age = input("how old is your child?")
child = client.Child(firstName, age)
child.show()
This correctly prints out the child, and seems to create the object within the Person class, but I can not figure out how to access this information through the Person class (client).
If I use something like child.firstName, it obviously only shows the last one entered, as the for loop is over-writing the child object every time. If I knew in advance how many children they would have, I could use something like child1, child2, etc, but since it is dynamic I don't know in advance.
Thanks in advance!
I'd design this with a single
Personclass likeThis prints out