python3 的lambda

bank.py

class Account:
    def __init__(self, name, number, balance):
        self.__name = name
        self.__number = number
        self.__balance = balance

    @property
    def name(self):
        return self.__name

    @property
    def number(self):
        return self.__number

    @property
    def balance(self):
        return self.__balance

    def deposit(self, amount):
        if amount <= 0:
            print('存款金額不得為負')
        else:
            self.__balance += amount

    def withdraw(self, amount):
        if amount > self.__balance:
            print('餘額不足')
        else:
            self.__balance -= amount

    def __str__(self):
        return "Account('{name}', '{number}', {balance})".format(
            name = self.__name, number = self.__number, balance = self.__balance
        )


>>> from bank import *
>>> acct = Account('Justin', '123-4567', 1000)
>>> deposit = lambda amount: Account.deposit(acct, amount)
>>> withdraw = lambda amount: Account.withdraw(acct, amount)
>>> deposit(500)
>>> withdraw(200)
>>> print(acct)
Account('Justin', '123-4567', 1300)
>>> 
[6]+  Stopped                 python3
Johnde-iPhone:object-oriented4 korekyourin$ python3
Python 3.4.4rc1 (v3.4.4rc1:04f3f725896c, Dec  6 2015, 10:40:23) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from bank import *
>>> acct = Account('Justin', '123-4567', 1000)
>>> deposit = acct.deposit
>>> withdraw = acct.withdraw
>>> deposit(500)
>>> withdraw(200)
>>> print(acct)

Account('Justin', '123-4567', 1300)


以上為Pyhton3 的lambda 範例 參考林信良老師 Python3技術手冊

留言

這個網誌中的熱門文章

佛教心靈哲學與心理治療 Buddhist Philosophy of Mind and Mental Healing

Buddhist Philosophy of Mind and Mental Healing 佛教心靈哲學與心理治療

佛教心靈哲學與心理治療 Buddhist Philosophy of Mind and Mental Healing