官术网_书友最值得收藏!

1.4 面向對象解決方案:初識類

代碼清單1-7展示了一種面向對象方法,該方法將一個賬戶的所有代碼和關聯數據組合到一起。這里有許多新概念,從下一章開始將詳細介紹所有細節。盡管你現在可能沒有完全理解這個示例,但是注意,這里把代碼和數據合并到一個腳本(稱為類)中。下面是你在本書中第一次接觸到的面向對象代碼。

代碼清單1-7:第1個Python類示例(文件: Account.py)

# Account class
 
class Account():
    def __init__(self, name, balance, password):
        self.name = name
        self.balance = int(balance)
        self.password = password
 
    def deposit(self, amountToDeposit, password):
        if password != self.password:
            print(‘Sorry, incorrect password’)
            return None
 
        if amountToDeposit < 0:
            print(‘You cannot deposit a negative amount’)
            return None
 
        self.balance = self.balance + amountToDeposit
        return self.balance
 
 
 
    def withdraw(self, amountToWithdraw, password):
        if password != self.password:
            print(‘Incorrect password for this account’)
            return None
 
        if amountToWithdraw < 0:
            print(‘You cannot withdraw a negative amount’)
            return None
 
        if amountToWithdraw > self.balance:
            print(‘You cannot withdraw more than you have in your account’)
            return None
 
        self.balance = self.balance - amountToWithdraw
        return self.balance
 
    def getBalance(self, password):
        if password != self.password:
            print(‘Sorry, incorrect password’)
            return None
        return self.balance
 
    # Added for debugging
    def show(self):
        print(‘       Name:’, self.name)
        print(‘       Balance:’, self.balance)
        print(‘       Password:’, self.password)
        print()

現在,思考這里的函數與前面的過程式編程示例有什么相似之處。函數的名稱與之前相同(show()、getBalance()、deposit()和withdraw()),但這里還有一些使用了self(或self.)的代碼。后面的章節將介紹它的含義。

主站蜘蛛池模板: 青冈县| 台东县| 安多县| 宽城| 汝城县| 扎鲁特旗| 华亭县| 枞阳县| 隆子县| 阜新市| 城固县| 苍南县| 仁怀市| 攀枝花市| 芜湖县| 汶川县| 灵寿县| 溆浦县| 色达县| 禄丰县| 绥德县| 精河县| 突泉县| 黎城县| 邵武市| 陆丰市| 东阿县| 鲁山县| 正阳县| 平江县| 永春县| 广灵县| 汽车| 合阳县| 探索| 文昌市| 平潭县| 南汇区| 吐鲁番市| 巴林左旗| 横山县|