31、编写一个Python的 Account 类,需要实现以下功能:1. 该类要能够跟踪已创建的该类实例的数量。2. 每次创建 Account 类的新实例时,打印一条消息显示当前已创建的实例数量。3. 在程序结束时,打印出已创建的账户数量。
以下是实现上述需求的Python代码示例:
class Account:
instance_count = 0
def __init__(self, account_number, account_holder, opening_balance, account_type):
Account.instance_count += 1
self.account_number = account_number
self.account_holder = account_holder
self.opening_balance = opening_balance
self.account_type = account_type
print(f'新的Account实例已创建,当前实例数量: {Account.instance_count}')
# 测试代码示例
if __name__ == '__main__':
account1 = Account('123456', 'John Doe', 1000, 'current')
account2 = Account('654321', 'Jane Smith', 2000, 'deposit')
print('Number of Account instances created:', Account.instance_count)
在上述代码中,我们定义了 Account 类,其中 instance_count 是类属性,用于跟踪已创建的实例数量。在 __init__ 方法中,每次创建新实例时, instance_count 会加1,并打印一条消息显示当前实例数量。最后,在测试代码部分,我们创建了两个 Account 实例,并在程序末尾打印出已创建的账户数量。
32、此练习涉及为CurrentAccount类添加错误处理支持。在CurrentAccount类中,不允许存入或取出负数金额。定义一个名为AmountError的异常/错误类,该类应将涉及的账户和错误消息作为参数。接下来,更新Account和CurrentAccount类中的deposit()和withdraw()方法,以便在提供的金额为负数时引发AmountError。你可以使用以下代码进行测试:try: acc1.deposit(-1) except AmountError as e: print(e)。
以下是实现上述需求的Python代码示例:
class Account:
def __init__(self, account_id, name, balance=0):
self.account_id = account_id
self.name = name
self.balance = balance
def deposit(self, amount):
if amount < 0:
raise AmountError(self, 'Cannot deposit negative amounts')
self.balance += amount
def withdraw(self, amount):
if amount < 0:
raise AmountError(self, 'Cannot withdraw negative amounts')
self.balance -= amount
class CurrentAccount(Account):
def __init__(self, account_id, name, balance=0, overdraft_limit=0):
super().__init__(account_id, name, balance)
self.overdraft_limit = overdraft_limit
def withdraw(self, amount):
if amount < 0:
raise AmountError(self, 'Cannot withdraw negative amounts')
if self.balance - amount < self.overdraft_limit:
raise BalanceError(self)
self.balance -= amount
class AmountError(Exception):
def __init__(self, account, message):
self.account = account
self.message = message
def __str__(self

最低0.47元/天 解锁文章
688

被折叠的 条评论
为什么被折叠?



