我正在尝试在 Person 类中创建一个 Child 类,但是当动态创建多个实例时,在创建后访问子对象时遇到问题。
例如,我询问用户他们有多少个孩子,然后我想为他们有的每个孩子创建一个内部子类的实例,并能够稍后访问该信息。
这是我迄今为止尝试过的一些代码,适用于一个孩子。但如果他们有超过 1 个孩子,我不知道如何访问这些信息。
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()
这正确地打印出了子级,并且似乎在 Person 类中创建了对象,但我不知道如何通过 Person 类(客户端)访问此信息。
如果我使用 child.firstName 之类的东西,它显然只显示最后输入的一个,因为 for 循环每次都会覆盖子对象。如果我事先知道他们会有多少个孩子,我可以使用 child1、child2 等,但由于它是动态的,我事先并不知道。
提前致谢!
我会用一个像
Person
这样的类来设计它
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)
打印出来
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)}