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!
Childhave to be an inner class? This would be much easier if it weren't.Childa different class at all? What makes a child different from a person?Personshould have aself.children: listvariable. Then you should have aPerson.add_child()method that appends the child to the list.Personmodel withparentsandchildrenlists (or sets).Childobject would have bothselfreferring to itself andPerson.selfreferring to the enclosing class. That's not how Python works. Inner classes are just separate classes. Except for the fact that you call the inner classPerson.Child, it really has no relationship to any particular person unless you specify that yourself.