類與實例

定義實例

一個實例本質(zhì)上是一個字典,里面包含的是:“方法名”-“函數(shù)”對。

def make_instance(cls):
        """Return a new object instance, which is a dispatch dictionary."""
        def get_value(name):
            if name in attributes:
                return attributes[name]
            else:
                value = cls['get'](name)
                return bind_method(value, instance)
        def set_value(name, value):
            attributes[name] = value
        attributes = {}
        instance = {'get': get_value, 'set': set_value}
        return instance
        
def bind_method(value, instance):
        """Return a bound method if value is callable, or value otherwise."""
        if callable(value):
            def method(*args):
                return value(instance, *args)
            return method
        else:
            return value

定義類

def make_class(attributes, base_class=None):
        """Return a new class, which is a dispatch dictionary."""
        def get_value(name):
            if name in attributes:
                return attributes[name]
            elif base_class is not None:
                return base_class['get'](name)
        def set_value(name, value):
            attributes[name] = value
        def new(*args):
            return init_instance(cls, *args)
        cls = {'get': get_value, 'set': set_value, 'new': new}
        return cls
        
        
def init_instance(cls, *args):
        """Return a new object with type cls, initialized with args."""
        instance = make_instance(cls)
        init = cls['get']('__init__')
        if init:
            init(instance, *args)
        return instance

栗子

def make_account_class():
        """Return the Account class, which has deposit and withdraw methods."""
        interest = 0.02
        def __init__(self, account_holder):
            self['set']('holder', account_holder)
            self['set']('balance', 0)
        def deposit(self, amount):
            """Increase the account balance by amount and return the new balance."""
            new_balance = self['get']('balance') + amount
            self['set']('balance', new_balance)
            return self['get']('balance')
        def withdraw(self, amount):
            """Decrease the account balance by amount and return the new balance."""
            balance = self['get']('balance')
            if amount > balance:
                return 'Insufficient funds'
            self['set']('balance', balance - amount)
            return self['get']('balance')
        return make_class(locals()) 

最后一句locals()返回一個當(dāng)前框架下的字典。

Account類可使用下句生成:

>>> Account = make_account_class()

子類關(guān)于繼承的實現(xiàn):

def make_checking_account_class():
        """Return the CheckingAccount class, which imposes a $1 withdrawal fee."""
        interest = 0.01
        withdraw_fee = 1
        def withdraw(self, amount):
            fee = self['get']('withdraw_fee')
            return Account['get']('withdraw')(self, amount + fee)
        return make_class(locals(), Account)


>>> CheckingAccount = make_checking_account_class() #子類的生成
>>> jack_acct = CheckingAccount['new']('Spock') #子類實例的生成
>>> jack_acct['get']('interest') #子類實例的方法調(diào)用
0.01
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 面向?qū)ο笞钪匾母拍罹褪穷悾–lass)和實例(Instance),必須牢記類是抽象的模板,比如Student類,...
    ppmoon閱讀 704評論 0 51
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,540評論 19 139
  • 3小時23分44秒,終于Q了。 時間往回倒3小時23分44秒,跨出起跑線的時候,沒有想到會是這么一個結(jié)果。 時間往...
    行者杰克閱讀 1,003評論 2 3
  • 為什么學(xué)一樣技能的時候,越學(xué)越感到迷惘,不知道還有多少沒學(xué)到, 關(guān)于吉他樂理心得表示很膚淺,時間不多,但是每...
    小師傅_88c3閱讀 1,908評論 1 3
  • 轉(zhuǎn)眼間70天馬上就要過去了,自控力第五期的三個核心訓(xùn)練營馬上就要陸續(xù)結(jié)營了。運動我參加了五期,冥想兩期,讀寫兩期。...
    Janetff閱讀 227評論 4 4

友情鏈接更多精彩內(nèi)容