物件導向 -- 類的組合

想吃橙子發表於2019-03-26

組合

將一個類的物件封裝到另一個類的物件的屬性中(一個類的物件是另一個類的物件的屬性),就叫組合 

例如 圓形類的物件是圓環類物件的 outer 屬性的值

   計算圓形相關資料的公式只和 Circle 類在一起

   其餘的用到公式的地方都是通過 Circle 類來使用的

   公式與其他類之間的關係是一個 '鬆耦合' 的關係

# 圓形類
from math import pi
class Circle:
    def __init__(self,r):
        self.r = r

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

    def perimeter(self):
        return 2*3.14*self.r

# 圓環類
class Ring:
    def __init__(self,r1,r2):
        if r1>=r2:
            self.outer = r1
            self.inner = r2
        else:
            self.inner = r1
            self.outer = r2

    def area(self):
        return 3.14 * self.outer ** 2 - 3.14 * self.inner ** 2

    def perimeter(self):
        return 2 * 3.14 * self.outer + 2 * 3.14 * self.inner
c = Circle(5)
r = Ring(6,8)

其他示例函式

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

    def date(self):
        return '%s-%s-%s'%(self.year,self.month,self.day)

class Student:
    def __init__(self,name,num,birth,in_shcool,start_day):
        self.name = name
        self.num = num
        self.birth = birth     # 組合
        self.in_school = in_shcool # 組合
        self.start_day = start_day # 組合

d1 = Date(1999,10,27)
d2 = Date(2019,1,9)
d3 = Date(2019,2,9)
feng = Student('馮磊',10086,d1,d2,d3)
print(feng.birth.year)
print(feng.birth.month)
print(feng.birth.day)
print(feng.birth.date())

feng.start_day.month +=1
print(feng.start_day.date())
class Student:
    def __init__(self,name,num,course):
        self.name = name
        self.num = num
        self.course = course

class Course:
    def __init__(self,name,price,period):
        self.name = name
        self.price = price
        self.period = period
python = Course('python',25000,'6 months')
s1 = Student('任世龍',10085,python)
s2 = Student('任希同',10084,python)
s3 = Student('董鵬',10083,python)
# print(s1.__dict__)
python.price = 30000
python.period = '7 months'
print(s1.course.price)

 

相關文章