【问题标题】:How to Manipulate Individual Object Instance Variables?如何操作单个对象实例变量?
【发布时间】:2014-12-07 11:32:06
【问题描述】:

我已经学习 Python 作为我的第一语言大约两周了,我喜欢它。我一直在使用 Learn Python the Hard way,但是当我遇到面向对象编程时,我的大脑几乎要爆炸了。我做了很多小时的研究,我以为我终于明白了要点,但现在我有点卡住了。

我创建了一个非常简单的银行程序,尝试使用类。我做得很好,直到我遇到了一个大问题。事实上,它可以工作(为简洁起见,我没有发布菜单设置,但只要我只有这三个对象,它就可以满足我的需求。)问题就在这里。

  1. 问题:如果有多个实例,如何操作实例值。 TLDR:我怎样才能不对对象引用进行硬编码? 请查看我的主要 BankAccount 类中的 Transfer 函数:我在对象(帐户)saccount.balance 和 paccount.balance 变量中进行了硬编码,但是如果有许多不同的帐户怎么办?我如何才能编辑他们的余额,也就是转账?


如何使 Transfer() 方法正确引用它们需要转到的实例?我这样问对吗?
我是否错误地使用了 OOP?
如果有多个用户或多个银行帐户怎么办?像“daccount”、“faccount”等我将如何管理他们的余额和转账?

请温柔一点……

这是我的主要课程:

class BankAccount:
    #### NO CLASS VARIABLES
    def __init__(self):
        self.balance = 500 #This is an instance variable

    def withdraw(self, amount): 
        self.balance = self.balance - amount
        print "You withdrew %d dollars\n" % amount
        return self.balance

    def deposit(self, amount): 
        self.balance += amount
        print "You deposited %d dollars\n" % amount
        return self.balance

    def transfer(self, amount):  ### Here is our problem
        print "Where would you like to transfer money from?" 
        answer = raw_input("1.) From CHECKINGS to SAVINGS\n2.)From SAVINGS to CHECKINGS\n >>>")
        if answer == "1":
            baccount.balance -= amount #What would I do if there were many accounts?
            saccount.balance += amount #I originally tried this as SavingsAccount.balance, but that would be a "Class Variable" correct?
        elif answer == "2":
            saccount.balance -= amount 
            baccount.balance += amount 
        else: 
            menu()**

    def printbal(self):
        print "Your balance is currently %d dollars." % self.balance
        return self.balance

这是我的两个子类(最低余额检查和储蓄)

class MinBalAccount(BankAccount): #This is a BankAccount and has a MinBal
    def __init__(self, minbalance): #This sets our minbalance during 'instantation'
        BankAccount.__init__(self) #This gives us the variable self.balance 
        print "ATM INITIALIZED. WELCOME TO SKYNET BANK"
        self.minbalance = minbalance #Sets the minimum balance for this minbalaccount

    def withdraw(self, amount):
        while self.balance - amount < self.minbalance: #THis allows for a loop, 
            print "Apologies, you must maintain a balance of 1.00" 
            print "If you withdraw %d from your current balance of %d it will leave you with a balance of %d dollars." % (amount, self.balance, self.balance - amount)
            print "Please Re-Enter The AMOUNT You would like to withdraw"
            amount = int(raw_input("\nAmount:"))

        BankAccount.withdraw(self, amount)
        self.printbal() #We can do this because we inherited it from out parent class. We could also write it as MinBalAccount.printbal(self) or BankAccount.printbal(self)


class SavingsAccount(BankAccount):
    def __init__(self,minbalance,balance):
        self.minbalance = minbalance
        self.balance = balance
paccount = BankAccount()
baccount = MinBalAccount(1.00)
saccount = SavingsAccount(300, 500)

【问题讨论】:

  • 如果您有很多 BankAccount 实例并且您想对所有这些实例进行 transfer(),您是否想知道该怎么做?
  • 与其全部转账...假设我有 'paccount = BankAccount() baccount = MinBalAccount() saccount = SavingsAccount iaccount = InvestingAccount()(我会创建一个菜单项“打开”并实例化一个 InvestingAccount 类对象)'我现在有一个额外的类实例(投资账户),我的转移方法无法处理。我如何才能允许我的用户对该帐户进行操作?

标签: python oop python-2.7 object instance


【解决方案1】:

如何使 Transfer() 方法正确引用他们需要去的实例?我这样问对吗?
我是否错误地使用了 OOP?

在 Python 中声明对象引用的方式与处理任何其他变量的方式相同,运行类的构造函数并将其分配给一个值。如果您想从一个帐户转移到另一个帐户(无论帐户如何),您希望将对象引用作为参数传递给方法中的函数(假设这些帐户彼此分开)。

考虑您的 BankAccount 类的设计:您当前正在使用您的转帐方法从两个固定帐户转帐。如果你想从当前的 BankAccount 对象(即“self”)转移到另一个账户(无论哪个被传递给方法),你可以这样编写你的方法:

def transferTo(self, otherAccount, amount):
  if (self.balance >= amount):
    self.balance -= amount
    otherAccount.balance += amount

然后当你调用这个方法时,你只需指明将资金转移到哪个账户。

baccount.transferTo(saccount, 100)

你就完成了!我建议将 IO 操作(例如要求用户输入)保留在这些方法之外,因为您可能希望执行不需要用户输入的传输。

您可以像对待任何其他值一样对待对象引用。因此,您可以将它们传递给任何方法,将它们放在列表中,等等。

如果有多个用户或多个银行帐户怎么办?像“daccount”、“faccount”等我将如何管理他们的余额和转账?

您应该将 AccountHolder 的概念与每个 BankAccount 分开。一个 AccountHolder 可能有多个 BankAccount,然后每个 BankAccount 都提供它自己的余额、数字等。您可以在类的方法中将类实例分配给实例变量。 AccountHolder 类应该有一个 BankAccount 对象的列表,并提供一些返回某些关键帐户的基本方法(例如 checksAccount() 方法)。像这样的构造函数对用户很有效:

class AccountHolder:
  def __init__(self, name):
    self.user_name = name
    self.checking = BankAccount()
    self.savings = MinBalAccount()

但是,我相信您的问题的关键是将对象引用作为参数传递给方法,从而使您可以更一般地处理 BankAccount 的每个实例。可以理解的是,这是您第一次真正接触 OOP,因此肯定会感到不知所措。祝你好运!

【讨论】:

  • 我认为这是我能找到的最接近我正在寻找的东西。我想我走错路了。我应该使转移方法更加通用(可扩展?)与目的地。因此,如果我要创建 AccountHolder 类并对其进行实例化,我可以将目标部分用作 self.checking/self.savings。这就是你的意思吗?
  • 听起来很准确。尽管您希望 transferTo() 方法位于 BankAccount 类中,并且 AccountHolder 类应该包含多个 BankAccount 对象。您可以通过使用方法签名中的参数作为对对象的引用来消除对每个帐户进行硬编码的需要。
【解决方案2】:

您必须修改您的传输函数。它需要 1) 金额 2) 目标账户

    def transfer(self, amount, destination):  ### Here is our problem
        self.balance -= amount
        destination.balance += amount

并在最后添加如下代码

print "Where would you like to transfer money from?" 
answer = raw_input("1.) From CHECKINGS to SAVINGS\n2.)From SAVINGS to CHECKINGS\n >>>")
amount = int(raw_input("Amount to transfer ? "))
if answer == "1":
    baccount.transfer(amount, saccount)
elif answer == "2":
    saccount.transfer(amount, baccount)
else: 
    menu()**

【讨论】:

    【解决方案3】:

    IMO 你在这里遇到了一个问题,因为transfer() 对于BankAccount 实例来说并不是一个很好的接口。 withdraw()deposit() 本身就有意义,但 transfer() 至少需要传递另一个参数,而不是硬编码全局变量(通常我尽量避免使用全局变量)。

    我会做的是有另一个类,例如User 拥有 paccountbaccountsaccount 变量,以及引导您完成菜单的 transfer()deposit()withdraw() 方法,例如:

    class User:
    
        def __init__(self):
            self._paccount = BankAccount()
            self._baccount = MinBalAccount(1)
            self._saccount = SavingsAccount(300, 500)
    
        def deposit(self, amount):
            num = input('Where do you want to deposit your money? 1) Savings 2) MinBal 3) Checking').strip()
            if num == '1':
               self._saccount.deposit(amount)
            ...
    
        def transfer(self, amount):
            print('Where would you like to transfer money from?')
            ...
    
    
    user = User()
    user.deposit(200)
    user.transfer(500)
    

    【讨论】:

    • 这似乎也是其他人所说的。我需要创建一个拥有自己帐户的用户类。这绝对是有帮助的。感谢您的回答 +1
    猜你喜欢
    • 2017-04-16
    • 2016-10-25
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多