pass object or use self.object?

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Apr 6 11:19:06 EDT 2010


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




More information about the Python-list mailing list