类 (组合)

 

 

组合

概念:一个类对象的属性 是 另外一个类的对象  说明这两个类是组合关系

事例1:计算两个同心圆的面积

from math import pi

class Circle:
    def __init__(self,r):
        self.r = r

    def area(self):
        return pi(self.r**2)

class Ring:
    def __init__(self,outer,inner):
        self.outer = Circle(outer)
        self.inner = Circle(inner)

    def area(self):
        return self.outer.area() - self.inner.area()
View Code

事例2:实例化老师

class Birthday:

    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day


class Teacher:

    def __init__(self,name,age,birth):
        self.name = name
        self.age = age
        self.birth = birth

birth = Birthday(1960,5,3)

xx = Teacher("苍老师",12,birth)

print(xx.birth.year)
View Code

 

posted @ 2018-03-06 11:23  golangav  阅读(287)  评论(0编辑  收藏  举报