pass object or use self.object?

Tim Arnold a_jtim at bellsouth.net
Wed Apr 7 18:50:20 CEST 2010


On Apr 6, 11:19 am, Jean-Michel Pichavant <jeanmic... at sequans.com>
wrote:
> 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
>
> > I ask because I've been told that the first case is easier to
> > understand. I never thought of it before, so I'd appreciate any
> > comments.
> > thanks,
> > --Tim
>
> Usually, when using classes as namespace, functions are declared as
> static (or as classmethod if required).
> e.g.
>
> class Foo:
>     @classmethod
>     def process(cls, document):
>         print 'process of'
>         cls.foo(document)
>
>     @staticmethod
>     def foo(document):
>         print document
>
> In [5]: Foo.process('my document')
> process of
> my document
>
> There is no more question about self, 'cause there is no more self. You
> don't need to create any instance of Foo neither.
>
> JM

Thanks for the input. I had always wondered about static methods; I'd
ask myself "why don't they just write a function in the first place?"

Now I see why. My situation poses a problem that I guess static
methods were invented to solve. And it settles the question about
using self.document since there is no longer any self. And as Bruno
says, it's easier to understand and refactor.

thanks,
--Tim



More information about the Python-list mailing list