On 04/06/10 23:52, Tim Arnold wrote: > Hi, > I have a few classes that manipulate documents. One is really a > process that I use a class for just to bundle a bunch of functions > together (and to keep my call signatures the same for each of my > manipulator classes). > > So my question is whether it's bad practice to set things up so each > method operates on self.document or should I pass document around from > one function to the next? > pseudo code: > > class ManipulatorA(object): > def process(self, document): > document = self.do_one_thing(document) > document = self.do_another_thing(document) > # bunch of similar lines > return document > > or > > class ManipulatorA(object): > def process(self, document): > self.document = document > self.do_one_thing() # operates on self.document > self.do_another_thing() > # bunch of similar lines > return self.document
Since in function in python is a first-class object, you can instead do something like: def process(document): # note: document should encapsulate its own logic document.do_one_thing() document.do_another_thing() And when you need some complex logic, you can easily elevate your function to a class: class Appender(object): def __init__(self, text): self.text = text def __call__(self, document): mtext = self.manipulate(document, text) document.append(mtext) and I think for your purpose, the mixin pattern could cleanly separate manipulation and document while still obeying object-oriented pattern that document is self-sufficient: # language with only single-inheritance can only dream to do this class Appendable(object): def append(self, text): self.text += text class Savable(object): def save(self, fileobj): fileobj.write(self.text) class Openable(object): def open(self, fileobj): self.text = fileobj.read() class Document(Appendable, Savable, Openable): def __init__(self): self.text = '' -- http://mail.python.org/mailman/listinfo/python-list