This repository was archived by the owner on Jun 4, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo3_encapsulation.py
More file actions
80 lines (66 loc) · 2.58 KB
/
demo3_encapsulation.py
File metadata and controls
80 lines (66 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
demo3: 封装 (Encapsulation)
场景:银行账户——保护余额不被直接修改
"""
from datetime import datetime
class BankAccount:
bank_name = "招商银行"
def __init__(self, owner: str, initial_balance: float = 0):
self.owner = owner # 公开
self._balance = initial_balance # 保护
self.__pin = "123456" # 私有
self._transactions = []
def deposit(self, amount: float) -> bool:
if amount <= 0:
print(f"存款金额必须大于0")
return False
self._balance += amount
self._log("存款", amount)
print(f"存款成功: +{amount:.2f}, 余额: {self._balance:.2f}")
return True
def withdraw(self, amount: float) -> bool:
if amount <= 0:
print(f"取款金额必须大于0")
return False
if amount > self._balance:
print(f"余额不足! 当前: {self._balance:.2f}")
return False
if amount > 5000:
print(f"单笔取款限额5000")
return False
self._balance -= amount
self._log("取款", amount)
print(f"取款成功: -{amount:.2f}, 余额: {self._balance:.2f}")
return True
@property
def balance(self) -> float:
return self._balance
def _log(self, type_: str, amount: float):
self._transactions.append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": type_,
"amount": amount,
"balance": self._balance
})
def __validate_pin(self, pin: str) -> bool:
return pin == self.__pin
def get_statement(self) -> list:
return self._transactions.copy()
def verify_pin(self, pin: str) -> bool:
return self.__validate_pin(pin)
if __name__ == "__main__":
print("=== 封装演示: 银行账户 ===\n")
account = BankAccount("KeepPush", 1000.0)
account.deposit(500)
account.withdraw(200)
account.withdraw(6000) # 超限额
account.withdraw(5000) # 余额不足
print(f"\n当前余额: {account.balance:.2f}")
print(f"\n--- 交易明细 ---")
for t in account.get_statement():
print(f" {t['time']} | {t['type']}: {t['amount']:.2f} | 余额: {t['balance']:.2f}")
print(f"\n--- 封装要点 ---")
print("1. self.owner: 公开属性, 直接访问")
print("2. self._balance: 保护属性, 通过deposit/withdraw操作")
print("3. self.__pin: 私有属性, 外部完全不可访问")
print("4. @property: 只读接口")