Search code examples
pythonclassinner-classes

Multiple instances of inner classes in Python


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!


Solution

  • I'd design this with a single Person class like

    class Person:
        def __init__(self, firstName, lastName, age):
            self.firstName = firstName
            self.lastName = lastName
            self.age = age
            self.children = set()
            self.parents = set()
    
        def add_child(self, child):
            self.children.add(child)
            child.parents.add(self)
    
        def __repr__(self):
            return f"Person({self.firstName!r}, {self.lastName!r}, age {self.age}, {len(self.children)} kids)"
    
    
    client = Person("Jake", "Blah", 31)
    child_1 = Person("Bob", "Blah", 1)
    child_2 = Person("Penny", "Blah", 2)
    client.add_child(child_1)
    client.add_child(child_2)
    print(client, "- kids:", client.children)
    print(child_1, "- parents:", child_1.parents)
    

    This prints out

    Person('Jake', 'Blah', age 31, 2 kids) - kids: {Person('Penny', 'Blah', age 2, 0 kids), Person('Bob', 'Blah', age 1, 0 kids)}
    Person('Bob', 'Blah', age 1, 0 kids) {Person('Jake', 'Blah', age 31, 2 kids)}