我在使用我试图制作的Python程序创建对象时遇到了问题。我不熟悉课程,所以不确定这是否是一个明显的问题。
我有两个班级:
class transaction():
def __init__(self, amount, name, typ, bank, date):
self.amount = Decimal(amount)
self.name = name
self.type = typ
self.bank = bank
self.date = date
self.day = date[8:]
self.month = date[5:7]
self.year = date[:4]
def compare(self, other_trans):
result = True
for attrib in other_trans.__dict__.keys():
if other_trans.__getattribute__(attrib) != self.__getattribute__(attrib):
result = False
break
return result
class full_date():
transactions = []
def __init__(self, lst, date):
for trans in lst:
if trans.date == date:
self.transactions.append(trans)
self.date = date
true_list = self.transactions[:]
duplicate = True
indexer = 0
while duplicate:
duplicate = False
for trans2 in self.transactions[indexer:]:
indexer = self.transactions.index(trans2)
testlist = self.transactions[:]
del testlist[testlist.index(trans2)]
for point in testlist:
if point.compare(trans2):
duplicate = True
del true_list[true_list.index(point)]
break
else:
duplicate = False
if duplicate:
break
self.transactions = true_list
transaction
应该是可操作的分析对象(金融交易),而full_date
是存储这些交易的对象。我在理论上知道我可以用字典做到这一点,但我用这个作为学习如何使用类的练习,__init__
函数给了我一个很好的方法来清理重复的事务。
但是,由于某些未知原因,当我尝试创建full_date类的多个实例时,它们只是复制自己,所以我最终得到的对象完全相同。
以下是我的尝试:
>>> y = transaction("12.51", "Amazon", "Other", "HSBC", "2014-12-06")
>>> x = transaction("12.49", "Amazon", "Other", "HSBC", "2014-12-06")
>>> w = transaction("12.50", "Amazon", "Other", "HSBC", "2014-12-06")
>>> lst = [w,x,y,z]
>>> b = full_date(lst, "2014-12-06") #a populated list so b.transactions should be populated
>>> b.transactions #and is
[<__main__.transaction object at 0x7fbcc37e5bd0>, <__main__.transaction object at 0x7fbcbf3a3e10>, <__main__.transaction object at 0x7fbcc37e5c10>]
>>> a = full_date([], "2014-12-06") #an empty list so a.transactions shouldn't be populated
>>> a.transactions #but it is
[<__main__.transaction object at 0x7fbcc37e5bd0>, <__main__.transaction object at 0x7fbcbf3a3e10>, <__main__.transaction object at 0x7fbcc37e5c10>]
当我在定义对象后尝试清除对象时,也会发生这种情况:
>>> b = None
>>> b = full_date([], "2014-12-05") #an empty list so b.transactions should be empty - also has the wrong date to make it more confusing
>>> b.transactions #but it is
[<__main__.transaction object at 0x7fbcc37e5bd0>, <__main__.transaction object at 0x7fbcbf3a3e10>, <__main__.transaction object at 0x7fbcc37e5c10>]
有谁知道为什么会这样?
编辑:找到答案。
class full_date:
def __init__(self, args):
self.transactions = []
... code
而不是:
class full_date:
transactions = []
def __init__(self, args):
... code