Python 類組合(composition)和彙總(aggregation)

來源:互聯網
上載者:User

下面一段代碼開始說起,知乎上有人問這個問題,說代碼看不懂。

    #coding:utf-8
    #書中一個例子簡單的短期利率類,折現是金融學中最基本的概念之一,在連續折現的固定短期利率世界中,日期t>0時未來現金流與當前日期t=0之間的折現因子為Do(t)=e(-rt)次方

    import numpy as np

    class short_rate(object):
        def __init__(self,name,rate):
            self.name=name
            self.rate=rate
        def get_discount_factors(self,time_list):
            time_list=np.array(time_list)
            return np.exp(-self.rate*time_list)


    class cash_flow_series(object):
        def __init__(self,name,time_list,cash_flows,short_rate):
            self.name=name
            self.time_list=time_list
            self.cash_flows=cash_flows
            self.short_rate=short_rate
        def present_value_list(self):
            df = self.short_rate.get_discount_factors(self.time_list)#想問這一行中為什麼可以這樣子不繼承第一個類可以調用第一個類的函數呢
            return np.array(self.cash_flows)*df
        def net_present_value(self):
            return np.sum(self.present_value_list())

    class cfs_sensitivity(cash_flow_series):
        def npv_sensitivity(self,short_rates):
            npvs=[]
            for rate in short_rates:
                sr.rate=rate #這個執行個體化rate的意思是?
                npvs.append(self.net_present_value())
            return np.array(npvs)

    short_rates=[0.01,0.025,0.05,0.075,0.1,0.125,0.15,0.2]
    cash_flows=np.array([-100,50,75])
    time_list=[0.0,1.0,2.0]

    sr=short_rate('r',0.05)


    print sr.get_discount_factors(time_list)

    sr.rate=0.05
    cfs=cash_flow_series('cfs0',time_list,cash_flows,sr)
    print cfs.present_value_list()

 

    cfs_sens=cfs_sensitivity('cfs',time_list,cash_flows,sr)

    npvs=cfs_sens.npv_sensitivity(short_rates)

    print npvs
上面的代碼命名很糟糕,提問者說是書Python金融大資料分析 (豆瓣) P350頁上的代碼。 稍微修改一下

    # coding:utf-8
    # 書中一個例子簡單的短期利率類,折現是金融學中最基本的概念之一,在連續折現的固定短期利率世界中,日期t>0時未來現金流與當前日期t=0之間的折現因子為Do(t)=e(-rt)次方

    import numpy as np


    class ShortRate(object):

        def __init__(self, name, rate):
            self.name = name
            self.rate = rate

        def get_discount_factors(self, time_list):
            time_list = np.array(time_list)
            return np.exp(-self.rate * time_list)


    class CashFlowSeries(object):

        def __init__(self, name, time_list, cash_flows, short_rate):
            self.name = name
            self.time_list = time_list
            self.cash_flows = cash_flows
            self.short_rate = short_rate

        def present_value_list(self):
            df = self.short_rate.get_discount_factors(
                self.time_list)  # 想問這一行中為什麼可以這樣子不繼承第一個類可以調用第一個類的函數呢
            return np.array(self.cash_flows) * df

        def net_present_value(self):
            return np.sum(self.present_value_list())


    class CfsSensitivity(CashFlowSeries):

        def npv_sensitivity(self, ShortRates):
            npvs = []
            for rate in ShortRates:
                sr.rate = rate  # 這個執行個體化rate的意思是?
                npvs.append(self.net_present_value())
            return np.array(npvs)

    ShortRates = [0.01, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.2]
    cash_flows = np.array([-100, 50, 75])
    time_list = [0.0, 1.0, 2.0]

    sr = ShortRate('r', 0.05)


    print sr.get_discount_factors(time_list)

    sr.rate = 0.05
    cfs = CashFlowSeries('cfs0', time_list, cash_flows, sr)
    print cfs.present_value_list()


    cfs_sens = CfsSensitivity('cfs', time_list, cash_flows, sr)

    npvs = cfs_sens.npv_sensitivity(ShortRates)

    print npvs
提問者提出其中df = self.short_rate.get_discount_factors(self.time_list) 這條語句不是很明白。

1、這個一個物件導向中類彙總的概念。
2、需要看CashFlowSeries 類的初始化方法中 self.short_rate = short_rate
short_rate 是ShortRate 類的執行個體,但你的代碼命名有問題,ShortRate 的執行個體調用自己的執行個體方法,沒有問題。

3、sr.rate = rate # 這個執行個體化rate的意思是?
要從下面語句看,sr 就是下面的sr 這個sr 是ShortRate的執行個體。sr 有執行個體屬性rate.
sr.rate = 0.05
cfs = CashFlowSeries('cfs0', time_list, cash_flows, sr)
類之間有多種關係,請大家看維基百科,類別圖 下面主要介紹彙總(Aggregation)以及組合(Composition)。

彙總(aggregation):指的是整體與部分的關係。通常在定義一個整體類後,再去分析這個整體類的組成結構。從而找出一些組成類,該整體類和組成類之間就形成了彙總關係。需求描述中“包含”、“組成”、“分為…部分”等詞常意味著彙總關係。

組合(composition):也表示類之間整體和部分的關係,但是組合關係中部分和整體具有統一的生存期。一旦整體對象不存在,部分對象也將不存在。部分對象與整體對象之間具有共生死的關係。

請看下面的代碼。類組合,Computer執行個體對象不存在了,內部組合的Cpu執行個體也不存在。彙總Computer執行個體對象不存在了,從初始化方法傳入的Cpu執行個體不屬Computer執行個體對象存在不存在的影響。

#! /usr/bin/env python
# coding:utf-8

'''
類對象組合關係
'''


class Cpu(object):

    def __init__(self):
        self.type = '286'


class Computer(object):

    def __init__(self):
        self.cpu = Cpu()  # 包含CPu類的執行個體對象

    def __del__(self):
        print "Cpu by by!"

old_computer = Computer()
del old_computer

#! /usr/bin/env python
# coding:utf-8

'''
類對象彙總關係
'''


class Cpu(object):

    def __init__(self):
        self.type = '286'


class Computer(object):

    def __init__(self, cpu):
        self.cpu = cpu  # 有一個CPu類的執行個體對象

    def __del__(self):
        print "沒有權力和Cpu by by!"

old_cpu = Cpu()
old_computer = Computer(old_cpu)
del old_computer

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.