Python基础的练习

-1 投票
1 回答
2938 浏览
提问于 2025-04-17 07:39

可能重复的问题:
Python基础 第8章 项目3

嗨,我是一个刚开始学习Python的新手程序员。
我之前也问过同样的问题,并且已经解决了,但我的答案并不完全符合问题的要求。

我需要帮助,想知道为什么我需要实现一个新方法,尽管我可以用其他方式来完成。

谢谢!

问题:

Bank类的__str__方法返回一个包含账户的字符串,但这些账户是随机顺序的。请设计并实现一个更改,使得账户按照名字的顺序放入字符串中。
[这是我不理解的部分]
(提示:你还需要在SavingsAccount类中定义一个新方法。)

class Bank(object):

    def __init__(self):
        self._accounts = {}
    def __str__(self):
        """Return the string rep of the entire bank."""
        pTemp =[]
        for i in xrange(len(SavingsAccount.temp)-1):
            if self._accounts.get(SavingsAccount.temp[i]).getName() >= self._accounts.get(SavingsAccount.temp[i+1]).getName():
                temp = SavingsAccount.temp[i]
                SavingsAccount.temp[i] = SavingsAccount.temp[i+1]
                SavingsAccount.temp[i+1] = temp
        for i in SavingsAccount.temp:
            pTemp.append(self._accounts[i])
        return '\n'.join(map(str, pTemp))

    def add(self, account): 
        """Inserts an account using its PIN as a key."""
        self._accounts[account.getPin()] = account
    def remove(self, pin):
        return self._accounts.pop(pin, None)
    def get(self, pin):
        return self._accounts.get(pin, None)
    def computeInterest(self):
        """Computes interest for each account and 
        returns the total."""
        total = 0.0
        for account in self._accounts.values():
            total += account.computeInterest()
        return total

class SavingsAccount(object):
    """This class represents a Savings account
    with the owner's name, PIN, and balance."""
    RATE = 0.02
    temp = []
    def __init__(self, name, pin, balance = 0.0):
        self._name = name
        self._pin = pin
        self._balance = balance
        SavingsAccount.temp.append(self)
    def __str__(self):
        result =  'Name:    ' + self._name + '\n' 
        result += 'PIN:     ' + self._pin + '\n' 
        result += 'Balance: ' + str(self._balance)
        return result
    def getBalance(self):
        return self._balance
    def getName(self):
        return self._name
    def getPin(self):
        return self._pin
    def deposit(self, amount):
        """Deposits the given amount and returns the
        new balance."""
        self._balance += amount
        return self._balance
    def withdraw(self, amount):
        """Withdraws the given amount.
        Returns None if successful, or an
        error message if unsuccessful."""
        if amount < 0:
            return 'Amount must be >= 0'
        elif self._balance < amount:
            return 'Insufficient funds'
        else:
            self._balance -= amount
            return None
    def computeInterest(self):
        """Computes, deposits, and returns the interest."""
        interest = self._balance * SavingsAccount.RATE
        self.deposit(interest)


def main():
    bank = Bank()
    bank.add(SavingsAccount("Zelda","1003",5000.00))
    bank.add(SavingsAccount("Wilma","1001",4000.00))
    bank.add(SavingsAccount("Fred","1002",1000.00))
    print bank

main()

1 个回答

1

我觉得这个问题希望你在 SavingsAccount 类里 定义排序规则,也就是说,要能判断一个 SavingAccounts 实例是排在另一个 SavingAccount 实例之前还是之后。我不想剧透太多,但如果我的提示不够,请告诉我 ;)

更新

另外,在 Python 中,字符串排序常见的错误是:az 之前,zA 之前,AZ 之前……

更新2

更多提示 ;)

你真正想要的是根据某个标准对 SavingAccount 的实例列表进行排序。有两种方法可以做到这一点:

  1. 让负责排序的人来处理
  2. 或者让你列表中的实例自己处理。

第二种方法通常更好,因为“要排序的类”应该比其他任何人都更清楚如何排序自己(这涉及到封装:不让外部的人控制你的类是如何工作的)。虽然这个问题不是特别清楚,而且我觉得例子也不太好,但他们希望你选择这个选项。

这个想法是银行应该做类似这样的事情:

class Bank(object):

    def __str__(self):
        """Return the string rep of the entire bank."""
        #get a sorted copy of the list 
        #using default SavingAccount comparison            
        pTemp =sorted(self._accounts) 
        return '\n'.join(map(str, pTemp))

SavingAccount 则包含了如何排序的信息。

你可能想看看 这篇来自 PythonInfo Wiki 的文章。还有:http://docs.python.org/reference/datamodel.html#object.__lt__

撰写回答