python物件導向

來源:互聯網
上載者:User

標籤:定義類   查看   mount   account   pytho   init   style   closed   python   

定義類

建立一個bank.py,為賬戶建立一個專用類,擁有專用屬性,然後讓儲存、提款等函數專屬於這個賬戶類的執行個體

在python中可以使用class來建立一個專用類

#定義Account類class Account:    passdef account(name, number, balance):    #建立acct執行個體,並設定相關屬性    acct = Account()    acct.name = name    acct.number = number    acct.balance = balance    return acctdef deposit(acct, amount):    if amount <= 0:        print(‘存款金額不得為負‘)    else:        acct.balance += amountdef withdraw(acct, amount):    if amount > acct.balance:        print(‘餘額不足‘)    else:        acct.balance -= amountdef desc(acct):    return "Account(‘{name}‘, ‘{number}‘, ‘{balance}‘)".format(        name = acct.name, number = acct.number, balance = acct.balance    )if __name__ == ‘__main__‘:    #建立賬戶,1000    myacct = account(‘heboan‘, ‘1234-567‘, 1000)    #存款200    deposit(myacct, 200)    #取款500    withdraw(myacct, 500)    #查看賬戶詳情    print(desc(myacct))
建立類

雖然我們定義了Account類作為賬戶的專用類,然而account()、deposit()、withdraw()、desc函數卻是在其他地方定義,明明它們都是與Account執行個體相關的操作,將相關的操作放在一起是設計時的一個基本原則,物件導向更是如此。

定義__init__()方法

account()函數,它定義了如何建立執行個體,以及執行個體建立後的相關屬性設定,這是每個Account執行個體都要經曆的初始化流程,可以將初始化流程使用__init__方法定義在類中

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

 

python物件導向

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.