总结:独立账户
Coddy 面向 C# 开发者的 Python 课程 课程的第 37 课,共 48 课。
挑战
入门实现具有独立状态且初始整数余额为非负数的 Account(owner, balance)。deposit(amount) 和 withdraw(amount) 返回更新后的余额。在修改状态前,对非正数金额或透支行为请抛出 ValueError。__str__ 返回 owner:balance。驱动程序读取两行 owner/balance、一个命令数量以及 index action amount 命令。Index 为 0 或 1,action 为 deposit 或 withdraw;owner 不包含空格。程序会打印每个结果或 invalid,然后按输入顺序打印两个账户。
C# 迁移检查点
与独立的 C# 引用对象一样,分别构建的 Python 账户绝不能共享可变状态。
C# 引用代码片段:可执行语句假设使用了 using System;,仅包含类型的片段说明了声明的契约。
var left = new System.Collections.Generic.List<int> { 5 };
var right = new System.Collections.Generic.List<int> { 5 };
left[0] += 2;
Console.WriteLine(right[0]);Python 模式
left = [5]
right = [5]
left[0] += 2
print(right[0])可编辑的实现文件:account.py。被锁定的 driver.py 是提供的启动器或输入/输出测试环境,必须保持不变。
保留提供的导入和精确的 API 名称。返回结果或抛出要求的异常;不要在这些实现模块中读取输入或进行打印。
亲手试试
from account import Account
accounts = []
for _ in range(2):
owner, amount = input().split()
accounts.append(Account(owner, int(amount)))
for _ in range(int(input())):
index, action, amount = input().split()
account = accounts[int(index)]
try:
if action == "deposit":
print(account.deposit(int(amount)))
else:
print(account.withdraw(int(amount)))
except ValueError:
print("invalid")
for account in accounts:
print(account)
面向 C# 开发者的 Python 课程中的所有课
自己练习: Python 在线编译器