- Python面向對象編程:構建游戲和GUI
- (美)艾維·卡爾布
- 350字
- 2023-06-29 17:17:47
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.)的代碼。后面的章節將介紹它的含義。
推薦閱讀
- iOS Game Programming Cookbook
- 從零開始構建企業級RAG系統
- Learning C# by Developing Games with Unity 2020
- 深入淺出Spring Boot 2.x
- 實戰低代碼
- Banana Pi Cookbook
- Unity 5.x By Example
- Instant Lucene.NET
- OpenResty完全開發指南:構建百萬級別并發的Web應用
- RealSenseTM互動開發實戰
- Delphi開發典型模塊大全(修訂版)
- Java 9 with JShell
- 用Python動手學統計學
- 從零開始學算法:基于Python
- Isomorphic JavaScript Web Development