为了账号安全,请及时绑定邮箱和手机立即绑定

寻找将对象放入“列表对象”的OOP Pythonic方法,而不是仅使用[list]

寻找将对象放入“列表对象”的OOP Pythonic方法,而不是仅使用[list]

慕森卡 2021-03-24 10:09:09
由于某种原因,我无法概念化如何使用Checkbook.class对象而不是“ ledger [list]”。什么是实现本准则目标的最佳实践方法?(是的,我也有其他“新手”问题,但是我很乐意得到一些建议。)import sysimport timetransNum=0ledger = []debitInput=['Check Number: ', 'Transaction Date: ',            'Payee: ', 'Amount: ', 'Memo (or Enter to skip): ']creditInput=['Check Number: ', 'Transaction Date: ',            'Source: ', 'Amount: ', 'Memo (or Enter to skip): ']# a Payee is a persistent record/lookup of current, past and new payeesclass Payee:    pass# a Source is a persistent record/lookup of current, past and new sourcesclass Source:    pass# a Checkbook is a collection of Transaction objects upon which queries may be performedclass Checkbook:    def __init__(self, newTrans):        pass# a Transaction is a collection of Debit and Credit objectsclass Transaction:    def __init__(self, chkNum, transDate, thirdParty, amount, memo=''):        self.chkNum = chkNum        self.transDate = transDate        self.memo=memo        self.thirdParty=thirdParty        self.amount=amount        self.transNum = transNumclass Debit(Transaction):    def __init__(self, *args):        Transaction.__init__(self, *args)        self.payee=self.thirdParty        del self.thirdParty        self.amount=int(self.amount)*-1class Credit(Transaction):    def __init__(self, *args):        Transaction.__init__(self, *args)        self.source=self.thirdParty        del self.thirdParty        self.amount=int(self.amount)while True:    transact = []    transNum += 1    choice=input('Posting debit [d], credit [c] or [x] to exit: ')    if choice == 'x': break    elif choice == 'd':        for field in debitInput:            field = input(field)            transact.append(field)        trans = Debit(transact[0], transact[1], transact[2], transact[3], transact[4])        ledger.append(trans)
查看完整描述

2 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

class Checkbook:


    def __init__(self):

        self.transactions = []    # Checkbook is just a wrapper around a list


    def __getitem__(self, index): # implementing [x]

        return self.transactions[index]


    def __setitem__(self, index, transaction): #implementing [x] = i

        self.transactions[index] = transaction


    def append(self, transaction): # implementing .append(x)

        self.transactions.append(transaction)


    def extend(self, transaction_list): # implementing .extend([x,y,z])

        self.transactions.extend(transaction_list)


    # and so on for every method which you want to support

或者,您可以继承list。


这是做作业吗?在Python中分配它是很愚蠢的。您永远不会真正想要继承list。在大学里,我有一个更好的练习,在该练习中,我必须重新std::vector使用模板,动态数组(带有malloc())和运算符重载……,这真有趣!该std::map演习是更好:)


查看完整回答
反对 回复 2021-03-30
  • 2 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信