首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python面向对象的固定账户

Python面向对象的固定账户
EN

Stack Overflow用户
提问于 2017-02-22 13:48:53
回答 1查看 48关注 0票数 0

我需要储蓄帐户不被更改为小于500的值。构造函数balance不应接受任何低于500的值。代码运行良好,一切正常。存取款方法可以正常工作,但我不知道如何防止余额小于500的变量访问储蓄帐户。

代码语言:javascript
复制
class BankAccount(object):
    def __init__(self):
        pass

    def withdraw(self):
        pass

    def deposit(self):
        pass


class SavingsAccount(BankAccount):
    def __init__(self, balance=500):
        self.balance = balance

    def deposit(self, deposit):
        if self.deposit > 0:
            self.balance += deposit
            return self.balance
        else:
            return "Invalid deposit amount"

    def withdraw(self, withdraw):
        if self.balance < withdraw:
            return "Cannot withdraw beyond the current account balance"
        elif (self.balance - withdraw) < 500:
            return "Cannot withdraw beyond the minimum account balance"
        elif withdraw < 0:
            return "Invalid withdraw amount"
        else:
            self.balance -= withdraw
            return self.balance


class CurrentAccount(BankAccount):
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, deposit):
        if self.deposit > 0:
            self.balance += deposit
            return self.balance
        else:
            return "Invalid deposit amount"

    def withdraw(self, withdraw):
        if withdraw < 0:
            return "Invalid withdraw amount"
        elif self.balance < withdraw:
            return "Cannot withdraw beyond the current account balance"
        else:
            self.balance -= withdraw
            return self.balance
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-22 14:04:52

代码语言:javascript
复制
class SavingsAccount(BankAccount):
    def __init__(self, balance=500):
        if balance < 500:
            raise ValueError("SavingsAccount balance must be at least 500")
        self.balance = balance

您还可以定义自定义异常:

代码语言:javascript
复制
class BalanceTooLowError(ValueError):
    """Raise if attempting to set an account balance to a disallowed value"""
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42383637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档