结婚、生子的Python程序

软件和网站开发以及相关技术探讨
回复
zzsu
帖子: 36
注册时间: 2006-01-24 13:15

结婚、生子的Python程序

#1

帖子 zzsu » 2008-01-02 13:57

程序:(human.py)

代码: 全选

class Person(object):
    def __init__(self, name):
        self.name = name

class Man(Person):
    def __init__(self, name):
        Person.__init__(self, name)
        self.children = []

    def marry(self, wife):
        self.wife = wife

    def procreate(self, baby):
        self.children.append(baby)

class Woman(Person):
    def __init__(self, name):
        Person.__init__(self, name)
        self.children = []

    def marry(self, husband):
        self.husband = husband

    def procreate(self, baby):
        self.children.append(baby)

class Child(Person):
    def __init__(self, name, father, mother):
        Person.__init__(self, name)
        self.father = father
        self.mother = mother

def marry(man, woman):
    man.marry(woman)
    woman.marry(man)

def procreate(father, mother, baby_name):
    baby = Child(baby_name, father, mother)
    father.procreate(baby)
    mother.procreate(baby)
    return baby
用例:

代码: 全选

from human import *
me = Man("James")
helen = Woman("Helen")
marry(me, helen)
tom = procreate(me, helen, "Tom")
helen.husband is me  [True]
me.wife is helen  [True]
me.wife.husband is me [True]
bin is me.children[0]
bin is helen.children[0]
bin.father is me
bin.mother is me
把争吵的时间用来学习或帮助别人。
blog
回复