班级设计:上次修改

时间:2010-07-22 22:21:49

标签: python class-design

我的课程:

class ManagementReview:
    """Class describing ManagementReview Object.
    """

    # Class attributes
    id = 0
    Title = 'New Management Review Object'
    fiscal_year = ''
    region = ''
    review_date = ''
    date_completed = ''
    prepared_by = ''

    __goals = [] # List of <ManagementReviewGoals>.
    __objectives = [] # List of <ManagementReviewObjetives>.
    __actions = [] # List of <ManagementReviewActions>.
    __deliverables = [] # List of <ManagementReviewDeliverable>.
    __issues = [] # List of <ManagementReviewIssue>.

    __created = ''
    __created_by = ''
    __modified = ''
    __modified_by = ''

__modified属性是isoformat中的日期时间字符串。我希望每次更新其他属性之一时,都会自动将该属性更新为datetime.now()。isoformat()。对于其他每个属性,我都有一个setter:

def setObjectives(self,objectives):
    mro = ManagementReviewObjective(args)
    self.__objectives.append(mro)

那么,是否有一种比添加如下行更简单的方法:

self.__modified = datetime.now().isoformat()

对每个人都有?

谢谢! :)

3 个答案:

答案 0 :(得分:5)

要在修改实例属性时更新__modified(如self.__objectives的示例所示),您可以覆盖__setattr__

例如,您可以将其添加到您的班级:

def __setattr__(self, name, value):
    # set the value like usual and then update the modified attribute too
    self.__dict__[name] = value
    self.__dict__['__modified'] = datetime.now().isoformat()

答案 1 :(得分:0)

也许在每个setter之前添加一个装饰器?

答案 2 :(得分:0)

如果你有一个方法将对这些属性所做的更改提交到数据库(比如save()方法或update_record()方法。就像那样),你可以只附加

self.__modified = datetime.now().isoformat()

就在它全部承诺之前,因为那是它唯一真正重要的时刻。