2
我有很多类(例如联系人),我也希望跟踪更改历史记录。以下是我的出发点。我想这是一个常见的使用案例,所以我会欣赏这里最佳实践的指导。这会是一个使用多重继承的好地方,那会是什么样子?Python继承“对象历史”的最佳实践
from datetime import date
class ContactHistory(object):
def __init__(self, contact, change_action, change_user_id, change_source):
self.name = contact.name
self.phone = contact.phone
self.email = contact.email
self.change_action = change_action
self.change_user_id = change_user_id
self.change_source = change_source
self.change_date = date.today()
def __repr__(self):
return '%s, %s, %s, %s, %s, %s, %s' % (self.name, self.email, self.phone, self.change_action, self.change_user_id, self.change_source, self.change_date)
class Contact(object):
def __init__(self, name, phone, email, change_user_id, change_source):
self.name = name
self.phone = phone
self.email = email
self.history = []
self.history.append(ContactHistory(self, 'created', change_user_id, change_source))
def update_phone(self, phone, change_user_id, change_source):
self.phone = phone
self.history.append(ContactHistory(self, 'phone updated', change_user_id, change_source))
def get_history(self):
return self.history
contact = Contact('Bill', '214-555-1212', 'me', 'admin page')
contact.update('972-555-1212', 'me', 'contact management page')
print contact.get_history()
可能http://stackoverflow.com/questions/8858525/track-changes-to-lists-and-dictionaries-in-python是有趣的。 – larsks
这个链接上有好东西@larsks ... @JackOfAll,也许你想查找'备忘录模式'?这不是你想要的直接,但也许你会从中得到一些新的想法? –