views:

51

answers:

3

My class:

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 = ''

The __modified attribute is a datetime string in isoformat. I want that attribute to be automatically to be upated to datetime.now().isoformat() every time one of the other attributes is updated. For each of the other attributes I have a setter like:

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

So, is there an easier way to than to add a line like:

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

to every setter?

Thanks! :)

+5  A: 

To update __modified when instance attributes are modified (as in your example of self.__objectives), you could override __setattr__.

For example, you could add this to your class:

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()
David Underhill
Instead of `self.__dict__[name] = value`, I'd probably do `object.__setattr__(self, name, value)`.
Matt Anderson
I would recommend that, but he isn't using a new-style class since his class doesn't derive from `object`.
David Underhill
A: 

Perhaps adding a decorator before each setter?

apalopohapa
+1  A: 

If you have a method that commits the changes made to these attributes to a database (like a save() method or update_record() method. Something like that), you could just append the

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

just before its all committed, since thats the only time it really matters anyway.

Jurassic_C