0

我有一个 BankAccount 类,我用它来创建一个允许用户存款、取款和查看余额的 GUI。

这是 BankAccount 类代码:

class BankAccount(object):
    """ creates a bank account with the 
        owner's name and a balance """
    def __init__(self, name, balance = 0):
        self.__name = name
        self.__balance = balance

    def getName(self):
        """ returns the owner's name """
        return self.__name

    def getBalance(self):
        """ returns the current balance """
        return round(self.__balance, 2)

    def deposit(self, amount):
        """ deposits amount into the account """
        self.__balance += amount

    def withdraw(self, amount):
        """ withdraws amount from the account
            returns 'overdrawn' if balance is too low """
        if self.__balance >= amount:
            self.__balance -= amount
        else:
            return 'overdrawn'

    def __str__(self):
        """ return a string representation of the account """
        return self.__name + ' has a balance of $' + str(round(self.__balance, 2))

这是 GUI 代码:

from tkinter import *
from bankAccountClass import BankAccount




class bankAccountGUI(Frame):
    def __init__(self):
        """Set up the GUI"""
        self.__balance= 0
        Frame.__init__(self)
        self.master.title('Bank Account')
        self.grid()

        depositLabel = Label(self, text= "Make Deposit")
        depositLabel.grid(row = 0, column = 0)
        self.depositVar= DoubleVar()
        depositEntry = Entry(self, textvariable= self.depositVar)
        depositEntry.grid(row = 0, column = 1)

        withdrawLabel= Label(self, text= "Make Withdrawal")
        withdrawLabel.grid(row = 1, column = 0)
        self.withdrawVar = DoubleVar()
        withdrawEntry= Entry(self, textvariable= self.withdrawVar)
        withdrawEntry.grid(row = 1, column = 1)


        button_1= Button(self, text = "Enter", command = self.deposit)
        button_1.grid(row = 0, column = 2)

        button_2= Button(self, text = "Enter", command = self.withdrawal)
        button_2.grid(row = 1, column = 2)


    def deposit(self):
        """event handler for button_1"""
        try:
            amount= self.depositVar.get()
            balance= BankAccount.getBalance(self)
            if amount <= 0:
                messagebox.showerror(message= 'Deposit must be greater than 0')
            else:
                balance= BankAccount.deposit(self, amount)
                messagebox.showinfo(title= "Current Balance",
                                    message= "$" + self.balance,
                                    parent= self)
        except ValueError:
            messagebox.showerror(message= "Invalid deposit amount")


    def withdrawal(self):
        """event handler for button_2"""
        try:
            amount= self.withdrawVar.get()
            balance= BankAccount.getBalance(self)
            if amount > self.balance:
                messagebox.showerror(message= "Insufficient funds")
            else:
                balance= BankAccount.withdraw(self, amount)
                messagebox.showinfo(title= "Current Balance",
                                    message= "$" + self.balance,
                                    parent= self)
        except ValueError:
            messagebox.showerror(message= "Invalid withdrawal amount")

def main():
    """instantiate and pop up the window"""
    bankAccountGUI().mainloop()

我收到一个错误,我真的不知道这意味着什么或如何解决它。

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 1442, in __call__
    return self.func(*args)
  File "/Users/tinydancer9454/Documents/python/bankAccountGUI.py", line 49, in deposit
    balance= BankAccount.getBalance(self)
  File "/Users/tinydancer9454/Documents/python/bankAccountClass.py", line 24, in getBalance
    return round(self.__balance, 2)
AttributeError: 'bankAccountGUI' object has no attribute '_BankAccount__balance'
4

2 回答 2

3

当你调用balance= BankAccount.getBalance(self)你的deposit函数时,你实际上在做的是访问类的getBalance()方法BankAccount,使用它未初始化,并尝试将不同的对象作为self. 当您通过访问类而不是实例来调用方法时,您必须给它一个self对象才能使其实际工作。BankAccount 方法期望它们的self对象是 BankAccount 对象。您正在向它传递一个不包含该__balance属性的 BankAccountGUI 对象。这就是它抛出该错误的原因。

你应该做的是创建一个 BankAccount 的实例,然后使用它的方法:

account = BankAccount()
balance = account.getBalance()

类似的东西。

于 2013-04-15T20:18:11.960 回答
0

_BankAccount__balance要了解错误消息中提到的变量,请参阅有关使用双下划线和“名称修改”的 Python 文档:

...由于类私有成员有一个有效的用例(即避免名称与子类定义的名称发生名称冲突),因此对这种称为名称修饰的机制的支持有限。表单的任何标识符__spam(至少两个前导下划线,最多一个尾随下划线)在文本上替换为_classname__spam,其中 classname 是当前类名,前导下划线被去除。

这个问题及其接受的答案也很丰富。

在这里解决这个问题的最简单方法是从类变量名中删除所有前导下划线。或者您可以self.__balanceBankAccount.getBalance()功能更改为self._BankAccount__balance.

编辑:您还将bankAccountGUI对象作为函数中的参数传递getBalance,如self. 它应该只是balance= BankAccount.getBalance(),没有self

于 2013-04-15T20:05:33.777 回答