如何操作单个对象实例变量?

时间:2014-10-12 23:00:59

标签: python oop python-2.7 object instance

我已经学习Python作为我的第一语言大约两周了,我喜欢它。我一直在使用学习Python的方法,但当我点击面向对象编程时,我的大脑就爆炸了。我做了很多小时的研究,我认为我终于得到了要点,但现在我有点卡住了。

我创建了一个非常简单的银行程序,试图使用Classes。我做得很好,直到遇到一个大问题。实际上,它是有效的(我没有发布菜单设置以简洁,但只要我只有这三个对象,它就能实现我想要的。)存在问题。

  1. 问题:如果有多个实例,如何操作实例值。 TLDR:我怎么能不硬编码对象引用? 请参阅我的主BankAccount类中的转移功能:我在对象(帐户)saccount.balance和paccount.balance变量中硬编码,但如果有许多不同的帐户怎么办?我如何编辑他们的余额,又称转移?

  2. 如何使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)
    

3 个答案:

答案 0 :(得分:0)

您必须修改传输功能。它需要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()**

答案 1 :(得分:0)

  

如何使Transfer()方法正确引用他们需要访问的实例?我问这个问题吗?   我错误地使用OOP吗?

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

考虑您的BankAccount类的设计:您目前正在使用转帐方式从两个固定帐户转帐。如果你想从当前的BankAccount对象(IE&#34; self&#34;)转移到另一个帐户(无论哪个帐户被传递给该方法),你都会这样编写你的方法:

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

然后,当您调用此方法时,您只需指明将资金转移到哪个帐户。

baccount.transferTo(saccount, 100)

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

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

  

如果有多个用户或多个银行帐户怎么办?喜欢&#34; daccount&#34;,&#34; faccount&#34;等我如何管理他们的余额和转账?

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

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

但是,我相信,您的问题的关键是将对象引用作为参数传递给方法,从而允许您更一般地处理BankAccount的每个实例。可以理解这是你第一次真正遇到OOP,所以肯定是压倒性的。祝你好运!

答案 2 :(得分:0)

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

我要做的是另一个班级,例如除Userpaccountbaccount方法外,还拥有saccounttransfer()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)
相关问题