Wrapping a class set method

Bengt Richter bokr at oz.net
Wed Jul 27 17:17:46 EDT 2005


On 27 Jul 2005 11:42:24 -0700, "snoe" <case.nelson at gmail.com> wrote:

>Hi there,
>
>I have the following simplified classes:
>
>class Project:
>    def __init__(self,pname):
>        self.devices = {} # Dictionary of Device objects
>        self.pname = pname
>
>    def setpname(self,pname):
>        self.pname = pname
>
>    def adddevice(self,dname):
>        self.devices[dname] = Device(self,dname)
>
>class Device:
>    def __init__(self,parent,dname):
>        self.parent = parent
>        self.dname = dname
>
>    def setdname(self,dname):
>        self.dname = dname
>
>Now, what I would like to do is wrap all of the set/add methods in a
>function that pickles the Project object. I would then save the pickled
>objects and use them to undo any changes to the above data structures.
>
>I have a suspicion that there's an easier way to do this than
>explicitly adding a Project.pickleme() call to the beginning of all of
>my set/add methods.
>
>So is there a way to wrap methods for this type of functionality or is
>there another way of doing this, maybe without using setter methods?
>
I would look into using properties with the same names as attributes of interest,
to store changes for possible undo/redo. For the devices attribute, you are not changing the
attribute per se, so you need a dict-like object that will do the state tracking when
you add devices. A dict subclass overriding __setitem__ should suffice for the usage you show.
Then you can give the classes undo/redo methods, or whatever. You could also use a special object
instead of a dict subclass, if you wanted some other interface.

Regards,
Bengt Richter



More information about the Python-list mailing list