类(三)组合

class family(object):
    family = 'this is a family of three'
    def __init__(self,mother,father):
        self.mother = mother
        self.father = father
    def menber_name(self):
        print(self.mother,self.father)

class Who(object):
    what = 'what'
    # brother = 'jack'
    def __init__(self,name,age,gender,family): ##将前面定义的family类,加入到Who类的数据属性中
        self.name = name
        self.age = age
        self.gender =gender
        self.family = family
    @property
    def information(self):
        print(self.name,self.age,self.gender)
        print(self.family.mother,self.family.father) ##通过self.family.mother调用family类中的数据
        return self.name
p0 = family('anna','jack')
p1 = Who('张三',18,'',p0)
a = p1.information

说明:Who类和family类没有重叠的部分,确实又相关联。这个人的基本信息是一个类,他的家庭成员是一个类。实现一个功能:这个人是谁,年龄,性别,以及他的家人姓名的功能。

组合:在一个类中以另外一个类的对象作为数据属性,称为类的组合。【将一个类,添加到另一个类的初始化中】

原文地址:https://www.cnblogs.com/liuhuacai/p/12601630.html