用Python表示家谱
时间: 2024-04-22 20:20:24 浏览: 10
在Python中,可以使用类和对象的概念来表示家谱。下面是一个简单的示例:
```python
class Person:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
self.children = []
def add_child(self, child):
self.children.append(child)
def get_children(self):
return self.children
def __str__(self):
return f"Name: {self.name}, Gender: {self.gender}, Age: {self.age}"
# 创建家庭成员对象
grandfather = Person("Grandfather", "Male", 70)
grandmother = Person("Grandmother", "Female", 68)
father = Person("Father", "Male", 40)
mother = Person("Mother", "Female", 38)
child1 = Person("Child1", "Male", 20)
child2 = Person("Child2", "Female", 18)
# 构建家谱关系
grandfather.add_child(father)
grandmother.add_child(father)
father.add_child(child1)
father.add_child(child2)
mother.add_child(child1)
mother.add_child(child2)
# 打印家谱信息
print(grandfather)
print(father)
print(child1)
print(child2)
```
这个示例中,我们定义了一个`Person`类来表示家庭成员。每个人都有姓名、性别和年龄属性,并且可以添加子女。通过创建对象并建立关系,我们可以构建一个简单的家谱树。最后,我们打印出每个人的信息。