getting the state of an object

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Oct 7 08:09:14 EDT 2012


On Sun, 07 Oct 2012 10:50:38 +0200, Franck Ditter wrote:

> Hi !
> 
> Another question. When writing a class, I have often to destructure the
> state of an object as in :
> 
> def foo(self) :
>     (a,b,c,d) = (self.a,self.b,self.c,self.d) 
>     ... big code with a,b,c,d ...

There's your problem right there: "big code". Methods should be small, 
ideally no more than a dozen lines or so. In my experience, small methods 
that have a very tight focus on doing one thing make it much easier to 
write, debug and maintain the method, and as a bonus having to write 
"self.a" is less of a burden.

I've just looked at one of my classes, picked randomly, and the largest 
method is twelve lines, the second largest is eight, and the average is 
three lines.


> So I use the following method :
> 
> def state(self) :
>     return (self.a,self.b,self.c,self.d)
> 
> so as to write :
> 
> def foo(self) :
>     (a,b,c,d) = self.state()
>     ... big code with a,b,c,d ...
> 
> This is probably not the best Python way to code, is it ? 

Not really the best. But I've seen worse.

If you *have* to write "big code with a,b,c,d" then this is probably 
acceptable. But better to refactor your big method into smaller methods 
that don't need to use self.a, self.b, self.c, self.d so many times that 
writing them explicitly is a nuisance. 

> Is there a
> simple way to get the *ordered* list of instance variables as given in
> the parameter list of __init__ ?

What you have written in method "state" is the simple way.

By the way, we prefer "instance attribute" or even "instance member" over 
"instance variable" here.



-- 
Steven



More information about the Python-list mailing list